llm-large-files 0.5.0 → 0.8.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.
Files changed (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,748 @@
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. When several questions share the signal, they
331
+ all throw the same reason, and `partialResultOf` gives none of them a result for it (since 0.7.1;
332
+ before, each got the result of the one that failed last): give each question an `AbortController`
333
+ of its own that the shared signal aborts with a new reason. Its `usage` is what was counted when the
334
+ question stopped: a request still running then, in an adapter that did not stop, may be billed by
335
+ the provider, and is not counted.
336
+
337
+ How the client side cancels a streamed answer is in [Web app](./web-app.md).
338
+
339
+ ## A request too large for the model
340
+
341
+ When the provider refuses a request as larger than the model takes (kind `context_overflow`), the
342
+ loop does not give up at once. The same holds for a request larger than the tokens the provider
343
+ lets through in a minute (OpenAI's and Groq's TPM, or a day's allowance): that allowance then
344
+ stands for the window.
345
+
346
+ 1. It takes the provider's count and window for the rest of the question, replaces tool results
347
+ with stand-ins (those of all but the last three tool rounds, then all but the last two, then all
348
+ but the last one, then all of them, as far as needed), and sends the request again, at most
349
+ twice in a question. The step says "The request was larger than the model takes: older tool
350
+ results were shortened, and it was sent again", or for an allowance, "The request was larger
351
+ than the provider allows in a minute: older tool results were shortened, and it was sent again".
352
+ 2. When shortening does not help (nothing is left to shorten, a model of the question may only grow
353
+ its conversation, such as Claude, or the request sent again shorter was refused again), and no
354
+ tool call of this question was answered and no text shown yet, it plans
355
+ the documents again for a smaller window and starts over, once. A document that was sent whole
356
+ may now be searched instead. The step says "The first request was larger than the model's
357
+ window of 131,072 tokens: the files were planned again to fit it", or "…for a smaller window".
358
+ For an allowance it says "The first request was larger than the 30,000 tokens a minute that the
359
+ provider allows: the files were planned again to fit it", or, when the message gives no limit,
360
+ "The first request was larger than the provider allows in a minute: the files were planned again
361
+ for a smaller request" ("a day" for an allowance per day).
362
+ What the first try used counts in `usage` and against `limits`.
363
+ 3. Otherwise it throws the error, with `partialResultOf`.
364
+
365
+ How the smaller window is worked out from the provider's numbers is in
366
+ [How it works](../how-it-works.md#a-request-too-large-for-the-model).
367
+
368
+ A part of a whole-file read that the model refuses as too large, for its window or for the minute's
369
+ allowance, is read as two halves, inside the tool. It does not throw. A refusal of a part that asked
370
+ for the larger output limit of a thinking model (32,768 tokens) turns that limit off for the model
371
+ only when the window, or the allowance, is no larger than it; otherwise later parts may still get
372
+ it.
373
+
374
+ When the error reaches you, one of these is the cause:
375
+
376
+ - **The conversation is too long.** The library does not shorten the text turns of the history.
377
+ Drop old turns, or start a new chat. See [Conversations](./conversations.md).
378
+ - **The model's window is smaller than the budget assumes** (1,000,000 tokens by default). Give the
379
+ adapter its `contextTokens`, so every question is planned for it. A gateway whose body limit is
380
+ below 10 MB answers 413: give the adapter its `maxRequestBytes`. `askGemini` has neither option:
381
+ set them in the budget instead, `createLargeFiles({ store, budget: { contextTokens: 128_000,
382
+ maxRequestBytes: 8_000_000 } })`, or in `budget` of `askGemini` for one question. See
383
+ [Costs and limits](./costs-and-limits.md).
384
+ - **The question names too many documents.** Ask about fewer.
385
+ - **The provider lets through fewer tokens a minute than a request needs** (OpenAI's TPM on a low
386
+ tier, Groq's free tier). `limitTokens` is that allowance. Give the adapter a `contextTokens` below
387
+ it, or ask the provider for a higher limit.
388
+ - **The provider's wording is not known**, and the error came as `invalid`. See
389
+ [The kind of a model error](#the-kind-of-a-model-error).
390
+
391
+ ## Empty or broken turns
392
+
393
+ In the tool loop (when a document is searched rather than sent whole, or a PDF's pages can be
394
+ looked at), two kinds of reply are asked for once more, with a short note at the end of the request
395
+ that says what was wrong:
396
+
397
+ - **A tool call that could not be read**: Gemini's `MALFORMED_FUNCTION_CALL` or
398
+ `UNEXPECTED_TOOL_CALL`. The step says "The model's tool call could not be read: it was asked to
399
+ send it again".
400
+ - **A first reply with nothing in it**: no text and no tool call, before any tool call of the
401
+ question was answered, and not cut off at the output limit or stopped by a filter. The step says
402
+ "The model's first reply was empty: it was asked again".
403
+
404
+ Without the second try, the answer would be written from the document cards alone and look like any
405
+ other. At most two such second tries are made in a question, and each takes one of
406
+ `limits.toolTurns`. When they are made, and which model keeps the note, is in
407
+ [How it works](../how-it-works.md#empty-or-broken-turns). When the second try is empty too, the
408
+ loop asks for the answer, as it does at the end of every question.
409
+
410
+ **The answer's second try.** The request for the answer (`toolChoice: "none"`) is asked for once
411
+ more when its reply has no text: when it is empty, or holds a tool call the model was told not to
412
+ make (Gemini's `UNEXPECTED_TOOL_CALL` or `MALFORMED_FUNCTION_CALL`, or calls from an adapter of
413
+ your own). The note at the end of that request is "Your last reply had no text. No tool can be
414
+ called in this reply: write the answer now, in text, from what is above.", and it is not kept. The
415
+ step says "The model's answer was empty: it was asked again", or "The model called a tool instead
416
+ of answering: it was asked again for the answer". It is one of the two second tries of the
417
+ question, and it can be one request past `limits.toolTurns`. It is not made after a refusal, a
418
+ filter, or a reply cut off at the output limit with nothing in it, nor once `limits.requests` or
419
+ `limits.inputTokens` is reached. When its reply has no text either, `answered` is false.
420
+
421
+ A single call that cannot be run is not a broken turn: arguments that are not a JSON object, a call
422
+ cut off at the output limit, a Claude call whose block never closed. It is answered with an error
423
+ that says why and asks the model to send it again, and the other calls of the turn run. A turn with
424
+ more calls than `limits.callsPerTurn` (8) runs the first 8 and answers the others "Not run: one turn
425
+ runs at most 8 tool calls. Send this call again if you still need it."
426
+
427
+ ## A stream cut off
428
+
429
+ A streamed reply ends with the provider's word for why it ended: a `finishReason` in Gemini's last
430
+ chunk, a `finish_reason` or `[DONE]` in an OpenAI-compatible stream, a `stop_reason` in Claude's. A
431
+ stream that closes without it was cut off on its way, by a proxy or a dropped connection. The
432
+ adapter does not take it for a whole reply: it throws an error with status 0, of kind
433
+ `unreachable`: "Gemini's reply ended before it was complete.", "The model's reply ended before it
434
+ was complete." or "Claude's reply ended before it was complete.". A connection that fails while the
435
+ reply arrives is the same, and so is a reply of HTTP 200 whose body is empty.
436
+
437
+ A stream that said it is whole (`[DONE]` on an OpenAI-compatible stream, `message_stop` on
438
+ Claude's) has its reply, whatever the connection does next. The body is read for one more second
439
+ at most, then cancelled, which closes the connection: a server or gateway that leaves it open does
440
+ not hold the request until `idleTimeoutMs`. A connection that breaks after the end marker loses
441
+ nothing either. 0.5.0 waited for such a connection to close, and took one that broke for a model
442
+ that could not be reached, with the whole answer already shown.
443
+
444
+ A reply asked for as a stream is read as one when its content type is `text/event-stream`. Of any
445
+ other type (a gateway that streams under `application/octet-stream`, or under none), it is read by
446
+ its first characters: as events when it starts with `data:` or a comment, as JSON when it starts
447
+ with `{` or `[` (Gemini's chunks in a list, as it sends them without `alt=sse`). A body that starts
448
+ with more than 65,536 characters of white space is read as JSON, whatever follows. A body that is
449
+ neither, such as an HTML page, is a reply that is not JSON: kind `invalid`, status 200, not sent
450
+ again. One event of a stream may hold 64,000,000 characters at most; a longer one ends the reply
451
+ with kind `invalid` and status 200, and is not sent again: it would come again.
452
+
453
+ An error the provider sends inside a stream that began with HTTP 200 takes the status the error
454
+ names, and is sent again or not by that status:
455
+
456
+ - On Gemini, its `code`. An error without one keeps the stream's 200, and is not sent again.
457
+ - On an OpenAI-compatible stream, its `code` or `type`: `context_length_exceeded` is 400 (kind
458
+ `context_overflow`), `insufficient_quota` 429 (kind `quota`), and `code` and `param` stay on the
459
+ error. One that names no status the adapter knows counts as a 500.
460
+ - On Claude, its `type`: `overloaded_error` 529, `rate_limit_error` 429, `api_error` 500,
461
+ `timeout_error` 408, `invalid_request_error` 400, `authentication_error` 401, `billing_error`
462
+ 402, `permission_error` 403, `not_found_error` 404, `request_too_large` 413 (kind
463
+ `context_overflow`). A type the adapter does not know is the server's failure, 500.
464
+
465
+ What happens next depends on what your user saw:
466
+
467
+ - **Nothing of that reply was passed to `onText`**: a turn of tool calls, an explorer's request, a
468
+ request without `onText`, a reply that failed before its first word. It is sent again, by the
469
+ retry rule.
470
+ - **Text of it was shown**: it is not sent again, since a second reply would repeat or contradict
471
+ what is on the screen. The error is thrown, and `partialResultOf(error).text` is the text that
472
+ was shown.
473
+
474
+ So in your UI, keep the text that arrived, mark it as cut off, and offer to ask again. This holds
475
+ for every error after the first word of an answer, not only for a cut stream.
476
+
477
+ ## Failures inside tools
478
+
479
+ The tools answer the model, not you. When a call fails, its result is `{ error: "…" }`, and the
480
+ model reads it and tries another way: a regex that does not compile, a page past the end of a PDF
481
+ (`view_pages`), a store that did not answer ("The document store could not be read (EIO). Try again."), a whole-file read
482
+ whose parts all failed. The question goes on, and can still be answered. A failed call shows:
483
+
484
+ - in `steps`, as a line that ends in " — failed: " and the error;
485
+ - in `toolTurns`, as a call whose `result.error` is a string;
486
+ - not in `evidence`, which lists only what was shown.
487
+
488
+ A whole-file read tells the model why a model request failed by the error's kind, its HTTP status
489
+ or the code of a connection that failed, never by the error's words: the provider's message, or an
490
+ HTTP client's, can name a project, a host, a masked key, or a URL with a key in it. The same words
491
+ are in its step and in `toolTurns`: "Read all of app.log for “Summarize.” — failed: Could not read
492
+ any part of app.log: The model refused the key or token it was sent (HTTP 401)." The reasons:
493
+
494
+ | The error | The reason |
495
+ |---|---|
496
+ | 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." |
497
+ | 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)." |
498
+ | 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)." |
499
+ | 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." |
500
+ | 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." |
501
+ | 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) |
502
+
503
+ These reasons go into "Could not read any part of app.log: …", "[This part could not be read: …]",
504
+ the note of a read whose last step failed (`notes_only`), and "The whole-file read of app.log failed
505
+ earlier in this question (…)". A failure to read a part's lines from the store keeps the store's
506
+ own message, which names no path or host: "The document store could not be read (EIO). Try again."
507
+ The provider's words belong in your log: log them in your own `fetch`, adapter or `generate`. To
508
+ give the model a specific reason from a `generate` of your own, throw an error with a `kind` or an
509
+ HTTP `status`.
510
+
511
+ A whole-file read that worked in part says so in its result (`parts_that_failed`, `notes_only`,
512
+ `notes_cut_short`, `answer_cut_short`). Its step ends in ", notes only" when the answer is only the
513
+ notes of the parts, and otherwise in ", incomplete" when notes or the answer were cut short. A read
514
+ that only lost parts has no such mark: its step ends in " — 12 parts, 3 relevant" as a complete
515
+ read's does, the failed parts among the 12. Look for `parts_that_failed` in its result in
516
+ `toolTurns`.
517
+
518
+ Most failed calls are the model's own mistakes, which it mends in its next turn. To see trouble on
519
+ your side, such as a store that fails often, log them:
520
+
521
+ ```ts
522
+ // result: what askWithFiles or askGemini returned.
523
+ const failed = result.toolTurns.flatMap((turn) => turn.calls).filter((call) => typeof call.result.error === "string");
524
+ for (const call of failed) console.warn(`Tool ${call.name} failed: ${String(call.result.error)}`);
525
+ ```
526
+
527
+ ## When there is no answer: `answered` and `finishReason`
528
+
529
+ A question can end without an error and without an answer. `answered` is false when the model's
530
+ last turn had no text:
531
+
532
+ - **The provider refused the prompt.** `blockReason` says why: Gemini's `promptFeedback.blockReason`
533
+ (such as "SAFETY"), "refusal" or "refusal: " and its category for Claude, "content_filter" for an
534
+ OpenAI-compatible reply that was filtered with nothing in it. Nothing more is asked after it.
535
+ - **The last reply ended without text**: cut off at the output limit before its first word, stopped
536
+ by a filter, or an answer with no text (empty, or a tool call) after its one second try.
537
+
538
+ `text` may then be empty, hold only a remark the model wrote before a tool call, or the start of a
539
+ reply the provider then refused. Show your own message instead.
540
+
541
+ `finishReason` is the provider's own word for how the last chat reply ended: "STOP", "MAX_TOKENS"
542
+ or "SAFETY" from Gemini, "stop", "length" or "content_filter" from an OpenAI-compatible server,
543
+ "end_turn", "max_tokens" or "refusal" from Claude. An answer can be `answered: true` and still be
544
+ cut off at the output limit. Tell the user, or raise the model's output limit (`maxOutputTokens` in
545
+ Gemini's `generationConfig`, the limit in `body` of `openAiCompatible()`, `maxTokens` of
546
+ `anthropic()`). Claude's `model_context_window_exceeded` means its window filled: shorten the chat
547
+ rather than raise the output limit.
548
+
549
+ ```ts
550
+ import type { AskResult } from "llm-large-files";
551
+
552
+ /** The words of the output limit, as each provider says them. */
553
+ const CUT_OFF = new Set(["MAX_TOKENS", "length", "max_tokens"]);
554
+
555
+ export function shownAnswer(result: AskResult): { text: string; note?: string } {
556
+ if (!result.answered) {
557
+ return { text: result.blockReason ? "This question was blocked by the model's safety filters." : "No answer this time. Ask again, or ask more precisely." };
558
+ }
559
+ if (result.finishReason === "model_context_window_exceeded") {
560
+ return { text: result.text, note: "The answer was cut off: the chat filled the model's window." };
561
+ }
562
+ if (result.finishReason !== undefined && CUT_OFF.has(result.finishReason)) {
563
+ return { text: result.text, note: "The answer was cut off at the model's output limit." };
564
+ }
565
+ return { text: result.text };
566
+ }
567
+ ```
568
+
569
+ ## Keeping what a failed question found
570
+
571
+ `askWithFiles` throws the error as it came, and what the question did until then is not lost.
572
+ `partialResultOf(error)` gives an `AskResult` with `answered: false`: the `steps`, `evidence`,
573
+ `toolTurns`, `usage` and `turns` of the question so far, its `plan` and `budget`, and the `text`
574
+ that was shown. The requests in `usage` were paid for: count them. Keep the tool rounds as you keep
575
+ those of an answered question (see [Conversations](./conversations.md)), so that asking again does
576
+ not search again.
577
+
578
+ It is undefined for an error that did not come from a question under way: `DocumentsNotFoundError`,
579
+ a `DocumentStoreError` while the documents were planned, a budget that cannot work, a last message
580
+ that is not the user's, and an abort whose reason is a string.
581
+
582
+ ```ts
583
+ import { askWithFiles, partialResultOf, type ModelAdapter } from "llm-large-files";
584
+
585
+ // recordUsage and keepToolTurns are your app's own: usage per user, tool rounds per chat session.
586
+ export async function askAndRecord(model: ModelAdapter, sessionId: string) {
587
+ try {
588
+ const result = await askWithFiles({ files, model, documentIds, messages, owner });
589
+ await recordUsage(owner, result.usage);
590
+ await keepToolTurns(sessionId, result.toolTurns);
591
+ return result;
592
+ } catch (error) {
593
+ const partial = partialResultOf(error);
594
+ if (partial) {
595
+ await recordUsage(owner, partial.usage);
596
+ await keepToolTurns(sessionId, partial.toolTurns);
597
+ }
598
+ throw error;
599
+ }
600
+ }
601
+ ```
602
+
603
+ ## Errors of uploads and of the store
604
+
605
+ `files.ingest` throws an [`IngestError`](../reference/library.md#ingesterror), with a message
606
+ written for the user and a `code` for your app, when it cannot take a file: it is empty
607
+ (`"empty"`), larger than `maxUploadBytes` (100 MB by default, `"too_large"`), has no text
608
+ (`"no_text"`), is a gzip or ZIP archive (`"compressed"`), is binary (`"not_text"`), is an Office
609
+ file of before 2007 or with a password (`"legacy_office"`), needs an optional dependency that is not
610
+ installed (`jszip` for DOCX, PPTX and XLSX, `unpdf` for PDF) or an `unpdf` that runs on this Node
611
+ (`"missing_dependency"`: the setup of the server, not the file, as in "The unpdf installed cannot
612
+ read PDF files on Node 20 (…). …"), or is a PDF without a text layer (see [PDFs](./pdfs.md)). Show
613
+ its message, or words of your own for its `code`. Until 0.8.0 it was a plain `Error`, with the same
614
+ message. A text file is never refused for its encoding: one that is
615
+ not UTF-8 is read in the encoding it was saved in, or as UTF-8 with the characters that are not
616
+ valid counted ([Text encodings](./pdfs.md#text-encodings)).
617
+
618
+ It throws a `TypeError` for an owner of `""`, spaces only or `null`: a mistake of your code, not of
619
+ the file. `createDocumentHandlers` answers it 500 `{ "error": "Upload failed (empty owner)." }`, or
620
+ `{ "error": "Upload failed (owner is not a string)." }` for an owner that is neither a string nor a
621
+ finite number, before it reads the upload ([Storage](./storage.md#how-ownership-works)).
622
+
623
+ A file the parser cannot read (a damaged DOCX, PPTX, XLSX or PDF) throws an `IngestError` of code
624
+ `"unreadable"` with the parser's message (jszip's, or that of pdf.js's `InvalidPDFException`), and
625
+ the parser's error as `cause`; an extractor of your own that throws an `Error` gets the same, with
626
+ the code its message gives. Those messages are not written for users: show "This file could not
627
+ be read." for the code `"unreadable"`. With `createIsolatedExtractors`, a file whose reader ran out
628
+ of memory or time is `"out_of_memory"` or `"timeout"`, readers that are all busy give `"busy"`,
629
+ answered `503` with `Retry-After`, and a reader that could not start at all (a `childScript` that
630
+ is not there) is not an `IngestError`, but an `Error` with `status` 500
631
+ ([node reference](../reference/node.md#createisolatedextractorsoptions)).
632
+
633
+ A store that fails while it writes throws its own error, as it came: its message may name a path or
634
+ a host, so log it and show a general message. `createDocumentHandlers` answers a file it cannot take
635
+ with 422 and the error's message, and a Node system error of the store (one with a `code` and a
636
+ `syscall`) with 500 and only its code ("Upload failed (ENOSPC)."). Any other store error, one
637
+ without a `status` (or `statusCode`) from 400 to 599, is answered 500 "Upload failed.", without its
638
+ message, and so is a thrown value that is not an `Error`. The handlers log nothing: log the error in
639
+ your store before you throw it. Two paths still answer a store's error 422 with its message, which
640
+ may name a host: an `ingest` of your own that throws a new error in its place, as `ingestInProcess`
641
+ in [Deployment](./deployment.md#uploads-and-ingest) does, and a route of your own, as in
642
+ [Web app](./web-app.md#filesingest-and-its-errors). So a custom store should throw an error with a
643
+ `status` and a message fit for the user (both are sent as they are): every path keeps that status.
644
+ See [the node reference](../reference/node.md#uploadrequest-response).
645
+
646
+ Every read of the store goes through the library: `prepare`, `getMeta`, `getOriginal`, the tools.
647
+ What the store throws there becomes a `DocumentStoreError`, which does not mean the document is
648
+ gone. A store's own `delete` and `sweep` pass on its error as it came. A document that is gone, or
649
+ of another owner, is not an error of the store: `prepare` lists it in `missing`, and `askWithFiles`
650
+ throws `DocumentsNotFoundError` for it. What a store must do is in [Storage](./storage.md).
651
+
652
+ ## Putting it together: a chat route
653
+
654
+ A route that answers a question in one JSON response, and turns each error into a status and a
655
+ message. Call `answerChat` from your route once the user is signed in and the body is read: `owner`
656
+ is the user, and `messages` and `documentIds` come from your chat session.
657
+
658
+ ```ts
659
+ import type { ServerResponse } from "node:http";
660
+ import { DocumentsNotFoundError, DocumentStoreError, errorKindOf, ModelRequestError, partialResultOf, type ToolTurn } from "llm-large-files";
661
+ import { askGemini, type ChatTurn } from "llm-large-files/gemini";
662
+
663
+ type Failure = { status: number; message: string; retryAfterSeconds?: number };
664
+
665
+ /** What to tell the user about an error of a question, and the HTTP status to answer with. */
666
+ export function toUserError(error: unknown): Failure {
667
+ if (error instanceof DocumentsNotFoundError) {
668
+ return { status: 404, message: "A file of this chat is no longer available. Attach it again." };
669
+ }
670
+ if (error instanceof DocumentStoreError) {
671
+ return { status: 503, message: "Your files could not be read just now. Try again in a moment." };
672
+ }
673
+ switch (errorKindOf(error)) {
674
+ case "context_overflow":
675
+ return { status: 413, message: "This chat is too long for the model. Start a new chat, or ask about fewer files." };
676
+ case "rate_limit": {
677
+ const wait = error instanceof ModelRequestError ? error.retryAfterMs : undefined;
678
+ return { status: 429, message: "The assistant is busy. Try again in a minute.", ...(wait ? { retryAfterSeconds: Math.ceil(wait / 1_000) } : {}) };
679
+ }
680
+ case "quota":
681
+ return { status: 503, message: "The assistant is not available right now." };
682
+ case "timeout":
683
+ return { status: 504, message: "The model took too long to answer. Try again." };
684
+ case "unreachable":
685
+ case "server":
686
+ return { status: 502, message: "The model could not answer just now. Try again." };
687
+ default:
688
+ // auth, invalid, and errors without a kind: your configuration or your code.
689
+ return { status: 500, message: "Something went wrong on our side. Try again later." };
690
+ }
691
+ }
692
+
693
+ export async function answerChat(response: ServerResponse, question: { owner: string; messages: Array<ChatTurn | ToolTurn>; documentIds: string[] }): Promise<void> {
694
+ const send = (status: number, value: unknown, headers: Record<string, string> = {}) => {
695
+ response.writeHead(status, { "Content-Type": "application/json", ...headers }).end(JSON.stringify(value));
696
+ };
697
+ const userLeft = new AbortController();
698
+ response.on("close", () => userLeft.abort());
699
+ const deadline = AbortSignal.timeout(15 * 60_000);
700
+
701
+ try {
702
+ const result = await askGemini({ files, endpoint, ...question, signal: AbortSignal.any([userLeft.signal, deadline]) });
703
+ if (!result.answered) {
704
+ const message = result.blockReason ? "This question was blocked by the model's safety filters." : "No answer this time. Ask again, or ask more precisely.";
705
+ send(200, { answered: false, message });
706
+ return;
707
+ }
708
+ send(200, { answered: true, text: result.text });
709
+ } catch (error) {
710
+ // What a failed question used was paid for: count it with the user's usage.
711
+ const partial = partialResultOf(error);
712
+ if (partial) console.info(`A failed question of ${question.owner} used`, partial.usage);
713
+ if (deadline.aborted) {
714
+ send(504, { error: "The question took too long. Ask again, or ask about less." });
715
+ return;
716
+ }
717
+ if (userLeft.signal.aborted) return; // nobody is waiting for the answer
718
+ // The provider's own message is for your log, not for the user.
719
+ console.error("A question failed", error);
720
+ const failure = toUserError(error);
721
+ send(
722
+ failure.status,
723
+ { error: failure.message, ...(error instanceof DocumentsNotFoundError ? { missing: error.ids } : {}) },
724
+ failure.retryAfterSeconds ? { "Retry-After": String(failure.retryAfterSeconds) } : {},
725
+ );
726
+ }
727
+ }
728
+ ```
729
+
730
+ With a streamed answer (Server-Sent Events), the status 200 is sent before the first word, and an
731
+ error cannot change it. Send the same message in an error event instead, and when
732
+ `partialResultOf(error)?.text` is not empty, say that the answer above it is incomplete. The events,
733
+ progress and cancelling are in [Web app](./web-app.md).
734
+
735
+ To see how your route handles each error without calling a real model, give it an adapter that
736
+ throws them: see [Testing](./testing.md).
737
+
738
+ ## Reference
739
+
740
+ - [Errors, retries and streams](../reference/errors-and-retries.md): `ModelRequestError`,
741
+ `ModelErrorKind`, `classifyModelError`, `errorKindOf`, `withRetry`, `RetryOptions`,
742
+ `RetryNotice`, `isRetryableStatus`, `retryAfterMs`, the default waits.
743
+ - [The tool loop](../reference/ask.md): `askWithFiles`, `AskResult`, `partialResultOf`,
744
+ `DocumentsNotFoundError`.
745
+ - [The library](../reference/library.md): `DocumentStoreError`, `ingest`, `prepare`.
746
+ - The adapters and their options: [Gemini](../reference/gemini.md),
747
+ [OpenAI-compatible](../reference/openai.md), [Claude](../reference/anthropic.md).
748
+ - [Troubleshooting](../troubleshooting.md): symptoms, causes and fixes.