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,1410 @@
1
+ # Troubleshooting
2
+
3
+ This page is for developers whose integration of llm-large-files does something they did not
4
+ expect. Each entry starts from what you see (an error message, an HTTP status, an answer that is
5
+ wrong), then gives the cause, the fix, and the page that explains it. The library's own messages
6
+ are quoted exactly. A provider's messages (Google's, OpenAI's, Anthropic's) are given as examples:
7
+ their wording is theirs and can change.
8
+
9
+ The samples assume what a question needs, as in [Getting started](./getting-started.md): `files`
10
+ from `createLargeFiles`, `endpoint` from `vertexAi()`, and the question's `documentIds`,
11
+ `messages` and `owner`.
12
+
13
+ - [Start here: what to log](#start-here-what-to-log)
14
+ - [Setup and install](#setup-and-install)
15
+ - [Uploads and formats](#uploads-and-formats)
16
+ - [Questions and answers](#questions-and-answers)
17
+ - [Errors from the model](#errors-from-the-model)
18
+ - [Performance and cost](#performance-and-cost)
19
+ - [Storage and several servers](#storage-and-several-servers)
20
+ - [Streaming](#streaming)
21
+
22
+ ## Start here: what to log
23
+
24
+ Most symptoms are explained by what the question returns. Log it while you look for a cause:
25
+
26
+ ```ts
27
+ import { askGemini } from "llm-large-files/gemini";
28
+
29
+ const result = await askGemini({ files, endpoint, documentIds, messages, owner });
30
+
31
+ console.log(JSON.stringify({
32
+ answered: result.answered, // false: the last turn had no answer
33
+ finishReason: result.finishReason, // why the last reply ended, in the provider's word
34
+ blockReason: result.blockReason, // why the provider refused the prompt, when it did
35
+ window: result.budget.contextTokens, // the window the documents were planned for
36
+ sentWhole: result.plan.inline.map((meta) => meta.name),
37
+ searched: result.plan.searchable.map((meta) => meta.name),
38
+ steps: result.steps, // every tool call, and what the loop did on its own
39
+ evidence: result.evidence, // the lines and pages each call showed the model
40
+ turns: result.turns,
41
+ usage: result.usage, // tokens and requests, in all and for each model
42
+ }, null, 2));
43
+ ```
44
+
45
+ - **`plan`** says which documents went into the prompt whole (`inline`) and which the model could
46
+ reach only through its tools (`searchable`). The model sees of a searched document only what its
47
+ searches and reads returned. `budget` is what the plan was made for: the library's budget, fitted
48
+ to the models.
49
+ - **`steps`** holds one line for each tool call, such as
50
+ `Search app.log (exact) for “timeout” — 12 matching lines`, or `… — failed: <reason>` when the
51
+ call failed, and a line for each thing the loop did on its own, such as
52
+ `Older tool results were shortened to make room in the request`. Each step is one line of plain
53
+ text that can quote the model's words: show it as text, never as markdown or HTML.
54
+ - **`turns`** counts the chat requests that were sent (one that failed counts, and one sent again
55
+ smaller after an overflow counts again); `usage.requests` counts the requests that were
56
+ answered, the part reads of a whole-file read included.
57
+
58
+ When a question throws, log the error's class, `kind`, `status` and message, and what the question
59
+ had done before it failed:
60
+
61
+ ```ts
62
+ import { DocumentsNotFoundError, DocumentStoreError, ModelRequestError, partialResultOf } from "llm-large-files";
63
+ import { askGemini } from "llm-large-files/gemini";
64
+
65
+ try {
66
+ await askGemini({ files, endpoint, documentIds, messages, owner });
67
+ } catch (error) {
68
+ if (error instanceof ModelRequestError) {
69
+ // status 0: no answer, a silent model (kind timeout), or a reply cut off on its way.
70
+ // status 200 and kind invalid: a reply that could not be read, such as a gateway's page.
71
+ // limitTokens and requestedTokens: the provider's numbers of an overflow.
72
+ console.error(error.name, error.kind, error.status, error.limitTokens, error.requestedTokens, error.message, error.cause);
73
+ } else if (error instanceof DocumentsNotFoundError) {
74
+ console.error("missing documents", error.ids);
75
+ } else if (error instanceof DocumentStoreError) {
76
+ console.error("store not readable", error.code, error.cause);
77
+ } else {
78
+ console.error(error);
79
+ }
80
+ // Undefined for an error raised before the question got under way (a missing document, a bad budget).
81
+ const partial = partialResultOf(error);
82
+ if (partial) console.error(partial.steps, partial.usage);
83
+ }
84
+ ```
85
+
86
+ What each error and `kind` means, and what to tell your user, is in
87
+ [Errors and reliability](./guides/errors-and-reliability.md).
88
+
89
+ ## Setup and install
90
+
91
+ ### `require("llm-large-files")` throws `ERR_REQUIRE_ESM`
92
+
93
+ **Cause.** The package is an ES module only. CommonJS code can load it with `require()` only on the
94
+ Node versions that load ES modules that way by default: 20.19 and later in Node 20, 22.12 and later
95
+ in Node 22, and 23 and later. Node 21 and Node 22.0 to 22.11 refuse. The library needs Node 20.19
96
+ or later in any case.
97
+
98
+ **Fix.** Upgrade Node, or load the package from CommonJS with `await import("llm-large-files")`
99
+ (and `import("llm-large-files/gemini")` and so on for the other entry points). In TypeScript this
100
+ needs `"module": "node16"` or `"nodenext"`: with `"commonjs"` the compiler turns `import()` into
101
+ `require()`, which fails the same way. The package has no CommonJS build.
102
+
103
+ See [Getting started](./getting-started.md).
104
+
105
+ ### A PDF, DOCX or PPTX upload fails: "needs the optional dependency"
106
+
107
+ `files.ingest` throws one of these, and the upload handler answers `422` with it:
108
+
109
+ - `Reading PDF files needs the optional dependency "unpdf".`
110
+ - `Reading DOCX, PPTX and XLSX files needs the optional dependency "jszip".` (until 0.8.0:
111
+ `Reading DOCX and PPTX files …`)
112
+
113
+ A package that is installed but fails to load, such as a version this Node cannot run, says so
114
+ since 0.8.0: `The optional dependency "unpdf" is installed but could not be loaded (…). Reinstall
115
+ it, or install a version this Node can run.` Its code is `"missing_dependency"` all the same.
116
+
117
+ A look at the pages of a PDF fails in `steps`, while uploads work:
118
+ `Look at report.pdf pages 12-14 — failed: report.pdf: Showing PDF pages needs the optional dependency "@cantoo/pdf-lib".`
119
+
120
+ **Cause.** The three packages are optional peer dependencies: `npm install llm-large-files` does
121
+ not install them. Or they are installed where you develop and missing where the server runs: kept
122
+ as `devDependencies` and left out of the production install, or missing from the image or the
123
+ bundle you deploy.
124
+
125
+ **Fix.** Install them as dependencies of the application that runs the upload route and the
126
+ questions: `npm install jszip unpdf @cantoo/pdf-lib` on Node 24 and later. On Node 20 and 22, name
127
+ a version of `unpdf` that runs there: `npm install jszip unpdf@1 @cantoo/pdf-lib` on Node 22, and
128
+ `npm install jszip unpdf@1.7.0 @cantoo/pdf-lib` on Node 20 (see
129
+ [below](#a-pdf-upload-fails-the-unpdf-installed-cannot-read-pdf-files-or-would-stop-the-whole-server)).
130
+ Install `@cantoo/pdf-lib` before PDFs are uploaded: without it nothing fails at upload, but the
131
+ text of a PDF is written without the line that marks a page with a picture
132
+ (`[Picture on this page. This text cannot show it.]`), and a document keeps the text it was
133
+ ingested with.
134
+
135
+ See [PDFs and other formats](./guides/pdfs.md).
136
+
137
+ ### A PDF upload fails: "The unpdf installed cannot read PDF files" or "would stop the whole server"
138
+
139
+ `files.ingest` throws one of these, and the upload handler answers `422` with it:
140
+
141
+ - `The unpdf installed would stop the whole server at the first PDF file on Node 22, so PDF files are not read. Install unpdf 1.6.1 or later, or run Node 24 or later.`
142
+ - `The unpdf installed would stop the whole server at the first PDF file on Node 20, so PDF files are not read. Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 24 or later.`
143
+ - `The unpdf installed cannot read PDF files on Node 20 (Serverless PDF.js bundle could not be resolved: ReferenceError: Iterator is not defined). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.`
144
+ The text in brackets is unpdf's own message, and differs between its versions.
145
+
146
+ The number is the major version of the Node that runs the server. DOCX, PPTX and text files are
147
+ read as before.
148
+
149
+ **Cause.** The version of `unpdf` that is installed cannot read PDFs on this version of Node, and
150
+ 0.6.0 checks it before it reads a PDF:
151
+
152
+ - unpdf 1.5.0 to 1.6.0 load a pdf.js that calls `Promise.try`, which Node 20 and 22 do not have. In
153
+ 0.5.0 the first PDF stopped the whole process, with a `TypeError` that nothing could catch.
154
+ - unpdf 1.9 and later, 2.x included, load a pdf.js that needs Node 22. On Node 20, every PDF failed
155
+ with unpdf's message alone.
156
+
157
+ unpdf 2 asks for Node 24, and on Node 24 a plain `npm install unpdf` installs it. On Node 22 and
158
+ later, a pdf.js that cannot be loaded for another reason fails with unpdf's message, as before.
159
+
160
+ **Fix.** Install the `unpdf` that runs on your Node, or move to the Node the message names:
161
+
162
+ | Node | `unpdf` to install |
163
+ |---|---|
164
+ | 20 | 1.4.0, or 1.6.1 to 1.8.1: `npm install unpdf@1.7.0`. 1.7.0 is the last that does not ask for Node 22. |
165
+ | 22 | 1.4.0, or 1.6.1 or a later 1.x: `npm install unpdf@1`. |
166
+ | 24 and later | Any version from 1.4.0, 2.x included: `npm install unpdf`. |
167
+
168
+ If the server loads pdf.js when it starts, as [Deployment](./guides/deployment.md#uploads-and-ingest)
169
+ shows, an `unpdf` that cannot load pdf.js on that Node (1.9 and later on Node 20) makes the start
170
+ fail instead. With unpdf 1.5.0 to 1.6.0 on Node 20 or 22, pdf.js loads and the server starts: PDFs
171
+ are then refused at upload, with one of the `would stop the whole server` messages above.
172
+
173
+ See [PDFs and other formats](./guides/pdfs.md#formats).
174
+
175
+ ### `npm install` stops with `ERESOLVE` over `unpdf`
176
+
177
+ **Cause.** llm-large-files 0.5.0 accepts `unpdf` ^1.4.0 only: with it, an install of unpdf 2, or
178
+ of 0.5.0 in an app that already has unpdf 2, stops with `ERESOLVE`. 0.6.0 accepts
179
+ `^1.4.0 || ^2.0.0`. So going back from 0.6.0 with unpdf 2 to 0.5.0 stops the same way
180
+ (`npm install llm-large-files@0.5.0`), and changes nothing.
181
+
182
+ **Fix.** Use 0.6.0. To go back to 0.5.0 from unpdf 2, install both in one command:
183
+ `npm install llm-large-files@0.5.0 unpdf@^1`, or restore `package.json` and `package-lock.json`
184
+ together.
185
+
186
+ See [PDFs and other formats](./guides/pdfs.md#formats).
187
+
188
+ ### `createLargeFiles` throws an error about `budget`
189
+
190
+ One of:
191
+
192
+ - `budget.contextTokens must be a number above 0, and is NaN.`
193
+ - `budget.reservedTokens (64,000) must be smaller than budget.contextTokens (32,000): nothing would be left for the conversation.`
194
+ - `budget.mapChunkTokens (100,000) must be smaller than budget.contextTokens (32,000): a part of a whole-file read would not fit the model.`
195
+
196
+ **Cause.** Every budget field must be a finite number above 0. `NaN` most often comes from
197
+ `Number(process.env.SOMETHING)` with the variable unset. The other two come from fields you set
198
+ that cannot work together: a field you set stays as you set it, and a field you leave out follows
199
+ `contextTokens`. The same errors come from the `budget` option of a question.
200
+
201
+ **Fix.** For a model with a smaller window, set `contextTokens` (and `maxRequestBytes`) and leave
202
+ the other fields out. Read numbers from the environment with a check:
203
+
204
+ ```ts
205
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
206
+
207
+ const contextTokens = Number(process.env.MODEL_CONTEXT_TOKENS);
208
+
209
+ export const files = createLargeFiles({
210
+ store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "./data/large-files"),
211
+ // Set the field only when the variable holds a number: Number(undefined) is NaN.
212
+ ...(Number.isFinite(contextTokens) && contextTokens > 0 ? { budget: { contextTokens } } : {}),
213
+ });
214
+ ```
215
+
216
+ See [`Budget`](./reference/library.md#budget) and [Costs and limits](./guides/costs-and-limits.md).
217
+
218
+ ### Importing the library fails in an edge runtime
219
+
220
+ **Cause.** The library runs on Node.js. It imports `node:crypto` and `node:fs` and uses `Buffer`,
221
+ which edge runtimes and browsers do not have.
222
+
223
+ **Fix.** Run the routes that upload and ask on the Node.js runtime. Browser code sends the file
224
+ and reads the answer stream; it never imports the library.
225
+
226
+ See [Web app](./guides/web-app.md).
227
+
228
+ ### `instanceof ModelRequestError` is false for a model error
229
+
230
+ **Cause.** Two copies of the package are installed (two versions, or a linked copy next to an
231
+ installed one). The error comes from the classes of one copy, and your `instanceof` checks against
232
+ the other.
233
+
234
+ **Fix.** Install one copy (`npm ls llm-large-files` lists them). Or test the kind with
235
+ `errorKindOf(error)`, which reads the `kind` field of any error that has one, whatever copy made it.
236
+
237
+ See [`ModelRequestError`](./reference/errors-and-retries.md#modelrequesterror).
238
+
239
+ ## Uploads and formats
240
+
241
+ ### `413`: "The file is larger than the 100 MB upload limit."
242
+
243
+ `createDocumentHandlers` answers `413` with `{ "error": "The file is larger than the 100 MB upload limit." }`.
244
+ `files.ingest`, called directly, throws `report.pdf is larger than the 100 MB upload limit.` The
245
+ number is your `maxUploadBytes` (100 MB by default).
246
+
247
+ **Cause.** The file is larger than `maxUploadBytes`. The handler tells it from `Content-Length`
248
+ before it reads anything, or stops keeping the bytes once the body passes the limit.
249
+
250
+ A `413` that comes before your handler runs, often with an HTML body, is not the library's: a proxy
251
+ in front of the server has its own limit (nginx's `client_max_body_size` is 1 MB unless you set it),
252
+ or a body parser mounted before the route has one (Express's `express.raw()` takes 100 kB unless
253
+ you set `limit`).
254
+
255
+ **Fix.** Raise `maxUploadBytes`, and the limit of each proxy in front of the route. Mount the upload
256
+ handler without a body parser: it reads the body itself. An upload is held in memory whole while it
257
+ is read and its text extracted, so a higher limit is more memory for each upload under way.
258
+
259
+ See [Web app](./guides/web-app.md) and [Deployment](./guides/deployment.md).
260
+
261
+ ### `400`: "Name the file with an X-File-Name header or a ?name= query parameter."
262
+
263
+ **Cause.** The upload request names no file. The name decides the format, and is shown to the
264
+ model.
265
+
266
+ **Fix.** Send `X-File-Name: encodeURIComponent(file.name)`, or `?name=` in the URL.
267
+
268
+ See [Web app](./guides/web-app.md).
269
+
270
+ ### `400`: "The upload body was already parsed by another middleware. …"
271
+
272
+ The whole message: `The upload body was already parsed by another middleware. Mount the upload route before body parsers, or send Content-Type: application/octet-stream.`
273
+
274
+ **Cause.** A body parser (`express.json()`, `express.urlencoded()`, a multipart parser) ran before
275
+ the handler and turned the file into an object.
276
+
277
+ **Fix.** Mount the upload route before the body parsers, and send the file with
278
+ `Content-Type: application/octet-stream`, which a JSON or form parser leaves alone. A `Buffer` in
279
+ `request.body`, as `express.raw()` leaves it, is used as the file.
280
+
281
+ See [Web app](./guides/web-app.md).
282
+
283
+ ### `500`: "Upload failed (empty owner)." or "Upload failed (owner is not a string)."
284
+
285
+ `createDocumentHandlers` answers the upload `500` with `{ "error": "Upload failed (empty owner)." }`
286
+ or `{ "error": "Upload failed (owner is not a string)." }`. It answers before it reads the body, and
287
+ logs nothing. `files.ingest`, called directly with such an owner, throws a `TypeError`:
288
+ `owner must be a string that is not empty or only spaces, such as the signed-in user's ID. To let anyone with the document's ID use it, leave owner out.`
289
+
290
+ **Cause.** Since 0.6.0 an owner of `""`, of spaces only, or `null` is refused. It would be one owner
291
+ shared by every caller without a user: each of them could read and delete the documents of the
292
+ others. 0.5.0 accepted it.
293
+
294
+ - **"empty owner"**: `getOwner` returned `""`, spaces, or `null`. Most often it does
295
+ `user?.id ?? ""` for a user who is not signed in, or reads a header that arrives empty
296
+ (`req.headers["x-user-id"]`).
297
+ - **"owner is not a string"**: `getOwner` returned, from JavaScript, something that is neither a
298
+ string nor a finite number: the user object (`req.user` in place of `req.user.id`), `true`, `NaN`,
299
+ an array.
300
+
301
+ A numeric owner is accepted, as before. `get`, `remove` and questions that pass the owner `""` work
302
+ as before, so documents that 0.5.0 stored with that owner stay readable until they expire.
303
+
304
+ **Fix.** Return the user's ID, not the user object. Where every upload needs a signed-in user,
305
+ throw an error with `status: 401` for a request without one. Only where anonymous uploads are
306
+ meant, return `undefined` for such a caller (`user?.id || undefined`): anyone who has the ID of
307
+ such a document may then use it.
308
+
309
+ See [`DocumentHandlerOptions`](./reference/node.md#documenthandleroptions) and
310
+ [Security](./security.md#ownership).
311
+
312
+ ### `422` for a file the library cannot read
313
+
314
+ `files.ingest` throws an [`IngestError`](./reference/library.md#ingesterror) written for your
315
+ user, with a `code` for your app (`"not_text"`, `"compressed"`, `"no_text"`…), and the upload
316
+ handler answers `422` with its message. The common ones:
317
+
318
+ | Message | What the file is |
319
+ |---|---|
320
+ | `This file looks binary, not text. Attach a text, log, PDF, Word, PowerPoint, Excel or HTML file.` | An image, an audio file, any other binary file. Until 0.8.0 the message ended `Attach a text, log, PDF, DOCX, or PPTX file.` |
321
+ | `This is a Word, Excel or PowerPoint file of before 2007 (.doc, .xls, .ppt), an Outlook message (.msg), or an Office file protected by a password and stored that way. None of these can be read: save it as .docx, .xlsx, .pptx, PDF or text, without a password, and attach that.` | A legacy `.doc`, `.xls` or `.ppt`, a `.msg`, or a DOCX, PPTX or XLSX saved with a password. New in 0.8.0: the first were "binary", the last failed as damaged files. |
322
+ | `This PDF is protected by a password, so it cannot be read. Open it, print it to a new PDF without the password, and attach that.` | A PDF with a password. New in 0.8.0: pdf.js said "No password given". |
323
+ | `This file is a ZIP archive. Extract it, then attach the text file you need.` | A ZIP, or a format that is a ZIP inside and is not DOCX, PPTX or XLSX: ODT, ODS. Until 0.8.0 an XLSX got it too. |
324
+ | `This file is gzip-compressed. Decompress it, then attach the text file inside.` | A compressed log, such as `app.log.gz`. |
325
+ | `report.txt is empty.` | A file of 0 bytes. |
326
+ | `report.docx did not contain any text.` | Nothing left once read: a DOCX of pictures, a file of blank lines. |
327
+ | `This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.` | A scan, while PDFs are not kept. |
328
+ | `The unpdf installed would stop the whole server at the first PDF file on Node 22, …` or `The unpdf installed cannot read PDF files on Node 20 (…). …` | Any PDF, while the `unpdf` installed cannot run on this Node. See [above](#a-pdf-upload-fails-the-unpdf-installed-cannot-read-pdf-files-or-would-stop-the-whole-server). |
329
+ | `This PDF has 6,200 pages, more than the 5,000 read from one file. Split it, and attach the part you need.` | A PDF of more than `maxPdfPages` pages (5,000 by default). Refused before any page is read. |
330
+ | `This PDF holds more than 100 MB of text, more than is kept from one file. Split it, and attach the part you need.` | A PDF whose text passes `maxTextBytes` (100 MB by default, or `maxUploadBytes` when that is larger). |
331
+ | `notes.txt holds more than 100 MB of text, more than is kept from one file. Split it, and attach the part you need.` | The same, from the text extractor or one of your own: a UTF-16 file can grow by half in UTF-8. |
332
+ | `This DOCX holds more than 32 million characters of text, more than is read from one file. Split it, and attach the part you need.` | A DOCX or PPTX of more than 32 million characters of text, about 10,000 dense pages. With `maxTextBytes` below that: `This DOCX holds more than 10 MB of text, more than is kept from one file.` |
333
+ | `report.pdf took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.` | The ingest took longer than `ingestTimeoutMs` (2 minutes by default). See [below](#an-upload-fails-took-too-long-to-read). |
334
+ | `This PDF lists the same page more than once. A file built that way can hold far more text than its size, so it is not read. Print it to a new PDF, and attach that.` | A PDF whose page tree lists one page several times. No PDF writer does this: a file of 3 KB built this way held 107 MB of text. |
335
+ | `This PDF draws more than 16 MB of text, over 100 times its size. A file that grows that much is not read: it may be built to exhaust the server.` | A PDF whose pages draw more than 100 times its size in text, past the first 16 MB: forms painted inside forms, many times over. Real PDFs hold less text than their size. |
336
+ | `This DOCX has more than 1,000,000 paragraphs, more than a document holds. It may be built to exhaust the server, so it is not read.` | A DOCX or PPTX of more than 1,000,000 paragraphs with text. |
337
+ | `This DOCX nests paragraphs more than 32 deep, which no document does. It may be built to exhaust the server, so it is not read.` | A DOCX or PPTX with paragraphs inside paragraphs, more than 32 deep. |
338
+ | `This DOCX has more than 20,000 parts, more than an Office document has. It may be built to exhaust the server, so it is not read.` | A DOCX or PPTX of more than 20,000 parts. They are counted the way JSZip will read them, whatever count the file gives: Office writes no file this large, a deck of 2,000 slides with notes and pictures has about 12,000. |
339
+ | `This DOCX lists its parts in a way that no Office program does: reading the list would take far more memory or time than an Office document needs. It may be built to exhaust the server, so it is not read.` | A DOCX or PPTX with more than 80,000 extra fields, or more than 8 MB of names, comments and extra-field data that JSZip would turn into text or go through byte by byte. The Office files we tried had at most 68 KB of them. |
340
+ | `This DOCX ends with a ZIP64 record that cannot be read, and reading it could hold the server without end. It may be built to exhaust the server, so it is not read.` | A DOCX or PPTX whose ZIP64 end record says it is longer than its fields: JSZip would read it in a loop that does not move on. |
341
+
342
+ **Fix.** Most messages say what the user can do. For a scanned PDF, keep PDFs
343
+ (`keepOriginals: ["pdf"]`): a scan of up to `scannedPdfPages` (30) pages is then accepted, and the
344
+ model reads it by looking at its pages. A longer scan needs OCR. To accept a format the library
345
+ refuses, such as an OpenDocument file (ODT, ODS), convert it to text or CSV before `files.ingest`,
346
+ or give a `text` extractor of your own that reads it: every file of a format the library does not
347
+ know goes to that one. To tell users in your own words or language, map `error.code`
348
+ ([`IngestError`](./reference/library.md#ingesterror)).
349
+
350
+ For a file past a limit, the user splits it and attaches the part the question is about. If your
351
+ users need larger files, raise `maxPdfPages` or `maxTextBytes` in `createLargeFiles`: the numbers
352
+ in the messages are yours. The last four messages are for files built to exhaust a server, not
353
+ written by Word, PowerPoint or a PDF printer: keep the limits. A file from a real program that
354
+ meets one is written the usual way once it is opened there and saved again, or printed to a new
355
+ PDF.
356
+
357
+ See [PDFs and other formats](./guides/pdfs.md#what-is-refused), which lists every refusal.
358
+
359
+ ### An upload fails: "took too long to read"
360
+
361
+ The whole message: `report.pdf took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.`
362
+ The number is your `ingestTimeoutMs`: in milliseconds below a second ("500 ms"), in seconds
363
+ below 2 minutes ("45 s"), in minutes from there ("2 min").
364
+
365
+ **Cause.** One `ingest` (extracting the text, its line index and its profile) took longer than
366
+ `ingestTimeoutMs`, 120,000 ms by default. Most often: a PDF with many pages that are slow to read;
367
+ an extractor of your own that waits on a slow service, such as OCR of a long scan; or a server
368
+ busy with other ingests, which each take their share of the same process. Nothing is stored.
369
+
370
+ **Fix.** For a file that is slow to read, the user splits it, or saves it as plain text. For OCR or
371
+ another slow extractor of your own, raise `ingestTimeoutMs` (0 sets no limit), run the ingest in a
372
+ background job ([Web app](./guides/web-app.md#long-ingests-in-the-background)), and pass
373
+ `input.signal` on to the service it calls, so that the request stops at the limit too. Bound the
374
+ ingests that run at once on one server ([Deployment](./guides/deployment.md#uploads-and-ingest)).
375
+ If you ingest in a process or a worker with a timer of its own, set that timer above
376
+ `ingestTimeoutMs`, so that the user gets this message and not yours.
377
+
378
+ See [`LargeFilesOptions`](./reference/library.md#largefilesoptions) and
379
+ [Custom extractors](./guides/pdfs.md#custom-extractors).
380
+
381
+ ### The server stops with "JavaScript heap out of memory" on a PDF
382
+
383
+ The process ends with `FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory`,
384
+ or with `FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory`,
385
+ during an upload of a PDF, or when the model looks at its pages, and every answer streaming on
386
+ that server stops.
387
+
388
+ **Cause.** pdf.js and `@cantoo/pdf-lib` build each object of the PDF in one step, and nothing
389
+ checks the memory an object takes before it is built. A file built for it holds objects far larger
390
+ in memory than in the file, often packed in an object stream: a PDF of 732 bytes, whose object
391
+ stream is unpacked twice, ran a heap of 512 MB out of memory at ingest, and a look at the pages of
392
+ one of 8 MB ran a heap of 256 MB out of memory. The limits on the number of objects a file declares
393
+ do not see such files. A look parses the whole file again, on the server that answers the
394
+ question, and takes more than the ingest did. On that server, what `@cantoo/pdf-lib` keeps also
395
+ adds up from file to file ([Memory grows with large files or many users](#memory-grows-with-large-files-or-many-users)).
396
+
397
+ A stream that unpacks to hundreds of MB takes that memory outside the heap, and no such line is
398
+ printed: a PDF of 1.6 KB was read with 20 MB of heap, while the process took 1.6 GB of memory and
399
+ the server was held for 6 s. A container with less than that left runs out of memory.
400
+
401
+ **Fix.** Read PDFs you do not trust in child processes with a heap limit of their own: pass the
402
+ `extractors` of [`createIsolatedExtractors`](./reference/node.md#createisolatedextractorsoptions) to
403
+ `createLargeFiles`. Such a file then runs out of the child's heap, the upload is answered `422`
404
+ "report.pdf needed more memory than is allowed for reading one file (512 MB). …" (code
405
+ `"out_of_memory"`), and your server goes on. For the memory a stream takes outside the heap, give
406
+ the server, or an ingest process of its own, a memory limit too, such as a container of its own
407
+ ([Deployment](./guides/deployment.md#uploads-and-ingest)). For their documents, do not offer
408
+ `view_pages` (`viewPages: false`), or keep no PDF originals. A larger heap only moves the size of
409
+ file that does it.
410
+
411
+ See [Security](./security.md#uploads) and the [measurements](./measurements.md#the-server).
412
+
413
+ ### Letters look wrong, or show as �, in a text file
414
+
415
+ The model quotes words in letters of another alphabet, or with `�`, or says that the file is not in
416
+ UTF-8. The document's metadata, and the summary the upload answered with, has `encoding` (such as
417
+ `"windows-1252"`), `replacedCharacters` (a count), or both.
418
+
419
+ **Cause.** A text, log, CSV, JSON or Markdown file that is not valid UTF-8 is never refused for its
420
+ encoding. Since 0.6.0 it is read one of two ways:
421
+
422
+ - **In an older encoding** (`encoding`), when its lines with letters fit one: windows-1255
423
+ (Hebrew), windows-1256 (Arabic), windows-1251 (Cyrillic), Shift_JIS (`"shift_jis"`, Japanese)
424
+ or windows-1252 (Western European). ISO-8859-8 is read as windows-1255, and ISO-8859-1 as
425
+ windows-1252. Lines of it that are valid UTF-8 are read as UTF-8.
426
+ - **As UTF-8**, as 0.5.0 read every file that was not UTF-16: when at least as many lines count as UTF-8 as count as
427
+ not (a line counts as UTF-8 when it holds at least as many characters of more than one byte as
428
+ characters that are not valid); when at most one line in 200 is not UTF-8, ASCII lines counted
429
+ (a log cut at a byte count, a stray byte, a binary body in a log line); and when no older
430
+ encoding fits.
431
+
432
+ Each character that was not valid in the encoding the file was read in is stored as `�`, and
433
+ counted in `replacedCharacters`. The model is told how the file was read: its card says
434
+ `This file is not in UTF-8. Its text was read as windows-1255: if its letters look wrong, ask the user to save it as UTF-8.`,
435
+ or `3 characters of this file were not valid UTF-8, and show as �.`, and a file sent whole says it
436
+ in its first frame line (`, read as windows-1255`).
437
+
438
+ Letters come out wrong where the encoding is not recognized, or is taken for another:
439
+
440
+ - Greek, Turkish, Central European (Polish, Czech, windows-1250), Icelandic, KOI8-R, the DOS code
441
+ pages (437, 850, 866), Chinese, Korean and Thai are not recognized: the file is read as UTF-8,
442
+ and almost every character of it outside ASCII is `�`, even one that windows-1252 has (Turkish
443
+ `güzel` comes out as `g�zel`). So is a Japanese file with few or no kana, such as names and
444
+ addresses in kanji only.
445
+ - Hungarian in windows-1250 or ISO-8859-2 is read as windows-1252, with õ and û in place of ő and
446
+ ű: a search for a word with ő or ű finds nothing.
447
+ - ISO-8859-15 is read as windows-1252 when it has no œ: its € comes out as ¤. In windows-1252, œ
448
+ is ½, which looks wrong inside a word (`c½ur`), and an encoding fits only when at most one word
449
+ or sign in 50 looks wrong: in French prose, one such word needs about 20 lines with accents
450
+ around it. So a file with œ in its words, a menu or a line or two of French, most often fits no
451
+ encoding: it is read as UTF-8, and each of its accented letters is `�`.
452
+ - A file of a line or two, or of one long line (minified JSON), can be read in a wrong encoding:
453
+ Greek capitals as windows-1251, `Straße` saved in DOS code page 850 as windows-1252 `Straáe`.
454
+ - In a log where at most one line in 200 is not UTF-8, those lines are `�` even when they are in
455
+ an older encoding.
456
+ - A document that 0.5.0 stored from a file in an older encoding holds `�` where its letters were:
457
+ 0.5.0 read every file that was not UTF-16 as UTF-8.
458
+
459
+ **Fix.** Ask the user to save the file as UTF-8 and attach it again: in Excel, Save As
460
+ "CSV UTF-8 (Comma delimited)"; in Notepad, Save As with the encoding UTF-8. Show `encoding` and
461
+ `replacedCharacters` of the upload's summary next to the file ("read as windows-1255", "3
462
+ characters could not be read"), so that the user sees it before asking. Ingest again the files
463
+ that 0.5.0 stored.
464
+
465
+ See [`DocumentMeta`](./reference/library.md#documentmeta) and
466
+ [Text encodings](./guides/pdfs.md#text-encodings).
467
+
468
+ ## Questions and answers
469
+
470
+ ### "The last message must be the user's."
471
+
472
+ **Cause.** `askWithFiles` and `askGemini` take the conversation with the new question last. This is
473
+ thrown when `messages` is empty (or `askGemini` got neither `messages` nor `contents`), or when it
474
+ ends with an answer or a tool round.
475
+
476
+ **Fix.** Append the question: `[...history, { role: "user", text: question }]`. Stored tool rounds
477
+ (`toolTurns`) go between the question they belong to and its answer, never after the new question.
478
+
479
+ See [Conversations](./guides/conversations.md).
480
+
481
+ ### `DocumentsNotFoundError`: "A document is no longer available: doc_…. Upload it again."
482
+
483
+ With several: `2 documents are no longer available: doc_…, doc_…. Upload them again.` The upload
484
+ handler's `get` answers `404` with `This file is no longer available.` for the same causes.
485
+
486
+ **Cause.** The question is thrown out before any model request because one of its `documentIds`:
487
+
488
+ - expired: documents are kept for `ttlMs`, 72 hours by default;
489
+ - was deleted;
490
+ - belongs to another `owner`, or has an owner while the question passes none. A document with an
491
+ owner is reported as missing, never as forbidden;
492
+ - was stored in a `MemoryDocumentStore` of another process, or of this one before it restarted;
493
+ - is not a document ID at all (`isDocumentId` is false for it).
494
+
495
+ **Fix.** Pass the same `owner` to the question as to the upload: the value `getOwner` returned for
496
+ the same user. Use a store that every server shares and that outlives a restart. Show the user which
497
+ files to attach again: `error.ids` names the IDs, and your chat knows their file names. A
498
+ document's `expiresAt` says when it goes.
499
+
500
+ See [Storage](./guides/storage.md) and
501
+ [`DocumentsNotFoundError`](./reference/ask.md#documentsnotfounderror).
502
+
503
+ ### In your own loop, a tool answers "doc_… is no longer available on the server" for a document that is there
504
+
505
+ The whole result: `{ "error": "doc_… is no longer available on the server. Ask the user to attach the file again." }`,
506
+ from `read_document`, `search_document`, `get_document_overview`, `analyze_whole_document` or
507
+ `view_pages`.
508
+
509
+ **Cause.** Besides a document that expired or was deleted after the question was planned: since
510
+ 0.6.0, `files.tools()` compares the owner stored with each document with the `owner` of the
511
+ `DocumentMeta` it was handed, and answers a mismatch as a document that is gone. Your loop passes
512
+ metadata that it built itself (from an ID, from its own database, from a `DocumentSummary`, which
513
+ has no owner) or that another owner's call returned. A document stored without an owner is not
514
+ checked.
515
+
516
+ **Fix.** Pass `tools()` the metadata that `prepare(ids, base, { owner })` returned
517
+ (`prepared.plan.searchable`, `prepared.viewable`), or `getMeta(id, { owner })`, with the owner of
518
+ the user who asks. `askWithFiles` and `askGemini` do this for you.
519
+
520
+ See [`files.tools`](./reference/library.md#filestoolsdocuments-options) and
521
+ [Security](./security.md#tool-scoping).
522
+
523
+ ### The answer says it found nothing, or ignores part of the file
524
+
525
+ Log the result ([Start here](#start-here-what-to-log)) and look for one of these:
526
+
527
+ - **The document is in `plan.searchable`.** It did not fit in the room for whole documents
528
+ (`inlineTokens`, 200,000 tokens by default, shared by the documents of the question, smallest
529
+ first), and the model saw only what its searches and reads returned (`evidence`). A keyword
530
+ search ranks passages by the words of the model's query; an exact search finds only the file's
531
+ own spelling. A model that searched with the wrong words did not see the answer. Ask with the
532
+ words the file uses, or give the search to a stronger model, as
533
+ [an explorer](./guides/explorer-model.md).
534
+ - **The question ran out of room or turns.** `steps` holds
535
+ `… — failed: Not run: there is no room left in this conversation for another tool result. …`, or
536
+ `turns` reached `limits.toolTurns` (12), or `usage` reached your `limits.inputTokens` or
537
+ `limits.requests`. The last request then asks the model to answer from what it has and to say
538
+ plainly what it could not find.
539
+ - **An explorer called no tool.** With an [explorer model](./guides/explorer-model.md), `steps` is
540
+ empty while `plan.searchable` lists documents: the explorer replied `DONE` at once, and the
541
+ answering model was told to say plainly what is not shown.
542
+ - **The answer is in a picture.** The text of a PDF page says
543
+ `[No text on this page. It may be a scan, a photo, or a chart.]` or
544
+ `[Picture on this page. This text cannot show it.]`. Without `view_pages` the model cannot see it
545
+ (see [below](#the-model-never-looks-at-a-page-or-says-it-cannot-see-it)).
546
+ - **The library does not read that part.** The pictures of DOCX and PPTX files are not read, nor
547
+ the charts of a workbook. Comments of a DOCX and speaker notes of a PPTX are read since 0.8.0:
548
+ a document ingested before keeps the text it had until it is uploaded again.
549
+ - **The document was not in the question.** Only the `documentIds` of this question are planned
550
+ and searchable.
551
+ - **The server cut the prompt.** Some local servers shorten a prompt longer than the context they
552
+ run with, without an error. The model answers from what was left. Set `contextTokens` on the
553
+ adapter to the window the server really runs with.
554
+
555
+ See [How it works](./how-it-works.md) for the plan and the tools, and
556
+ [Tools](./reference/tools.md) for what each tool returns.
557
+
558
+ ### The answer quotes text that the document does not show
559
+
560
+ The model cites a line that starts `[Hidden text, not shown in the document]`, or a slide whose
561
+ heading says `(hidden, not shown in the slide show)`, and the user does not see it in the file.
562
+
563
+ **Cause.** Since 0.6.0 the text of a DOCX run that Word hides (`<w:vanish/>`) is kept and marked: it
564
+ comes after the text of its paragraph that shows, each of its lines starting with that mark. A
565
+ slide that the slide show skips keeps its text, and its heading says so. The mark tells the model
566
+ what a reader of the document does not see. It is a hint: text hidden through a style, white or
567
+ tiny text, and hidden shapes are read as ordinary text, without it.
568
+
569
+ **Fix.** Nothing breaks. To have the model leave hidden text out of its answers, or name it as
570
+ hidden, say so in your `system` instruction.
571
+
572
+ See [PDFs and other formats](./guides/pdfs.md#docx-and-pptx).
573
+
574
+ ### `answered` is `false`
575
+
576
+ **Cause.** The model's last turn had no text:
577
+
578
+ - **The provider refused the prompt.** `blockReason` says why: Gemini's own reason, Claude's
579
+ `refusal` (with its category: `refusal: <category>`), or `content_filter` from an
580
+ OpenAI-compatible server. Nothing more is asked after a refusal.
581
+ - **The reply was cut off before any text.** `finishReason` is `MAX_TOKENS` (Gemini), `length`
582
+ (OpenAI-compatible) or `max_tokens` (Claude): the output limit was spent, most often on thinking.
583
+ - **The reply was filtered** in the request that had to be the answer.
584
+ - **The request for the answer came back without text twice.** A reply to it that is empty, or
585
+ holds a tool call the model was told not to make (Gemini's `UNEXPECTED_TOOL_CALL` or
586
+ `MALFORMED_FUNCTION_CALL`), is asked for once more, with a note that is not kept. `steps` then
587
+ holds `The model's answer was empty: it was asked again` or
588
+ `The model called a tool instead of answering: it was asked again for the answer`. That second
589
+ try is one of the two a question may make, and is not made after a refusal, a filter, a reply
590
+ cut off with nothing in it, or once `limits.requests` or `limits.inputTokens` is reached. In
591
+ 0.5.0 the question ended at the first empty reply to the request for the answer.
592
+
593
+ `text` is then empty, holds only a remark the model made before a tool call, or holds the start of
594
+ a reply the provider then refused.
595
+
596
+ **Fix.** Do not show `text` as the answer: show your own message, and log `finishReason` and
597
+ `blockReason`. For a cut-off reply, raise the output limit or lower the thinking. The same prompt
598
+ asked again is most often refused again.
599
+
600
+ See [Errors and reliability](./guides/errors-and-reliability.md).
601
+
602
+ ### The answer stops in the middle of a sentence
603
+
604
+ `answered` is `true`, and `finishReason` is `MAX_TOKENS`, `length` or `max_tokens`.
605
+
606
+ **Cause.** The answer reached the output limit: `maxOutputTokens` in Gemini's `generationConfig`,
607
+ `max_completion_tokens` or `max_tokens` in the `body` of `openAiCompatible()`, `maxTokens` of
608
+ `anthropic()` (64,000 by default). A model that thinks counts its thoughts in that limit. The library
609
+ does not continue a reply that was cut.
610
+
611
+ **Fix.** Raise the limit, or lower the thinking (`thinkingConfig` for Gemini). Tell the user when
612
+ `finishReason` says the answer was cut.
613
+
614
+ See [Gemini API and Vertex AI](./guides/vertex-and-gemini.md),
615
+ [OpenAI-compatible endpoints](./guides/openai-compatible.md) and [Claude](./guides/anthropic.md).
616
+
617
+ ### The answer begins with "Let me search the log…"
618
+
619
+ **Cause.** Without an explorer, `text` is everything the model wrote, and that includes a remark it
620
+ made before a tool call. Streaming shows it as it comes.
621
+
622
+ **Fix.** Accept it, ask for no remarks in your `system` instruction, or use an
623
+ [explorer model](./guides/explorer-model.md): the explorer's words are never shown, and `text` is
624
+ only what the answering model wrote.
625
+
626
+ ### The model never looks at a page, or says it cannot see it
627
+
628
+ `steps` holds no `Look at …` line, or holds one and the model then says it cannot see the page.
629
+
630
+ **Cause.** The model gets `view_pages` for a PDF only when all of these hold:
631
+
632
+ - `keepOriginals` lists `"pdf"`, and the store has `putOriginal` and `getOriginal`
633
+ (`FileDocumentStore` and `MemoryDocumentStore` have both);
634
+ - the document was ingested after that: one ingested before has no file kept
635
+ (`meta.originalKept` is not `true`);
636
+ - every model of the question can be sent a file: not `openAiCompatible()` without `pdfInput`, not
637
+ `anthropic({ toolFilePlacement: "none" })`;
638
+ - the question does not pass `viewPages: false`.
639
+
640
+ A model that has the tool and does not call it may have found the answer in the text.
641
+
642
+ A model that looked and says it cannot see the page is most often Gemini 2.5 with the default
643
+ `toolFilePlacement: "inside"`: it accepts the pages inside a function response, bills them, and
644
+ does not see them.
645
+
646
+ **Fix.** Turn on `keepOriginals: ["pdf"]` and upload the PDFs again. For Gemini 2.5, pass
647
+ `toolFilePlacement: "beside"` to `askGemini` or `gemini()`. With `@cantoo/pdf-lib` missing, every
648
+ look fails: install it ([above](#a-pdf-docx-or-pptx-upload-fails-needs-the-optional-dependency)).
649
+
650
+ See [PDFs and other formats](./guides/pdfs.md).
651
+
652
+ ### Whole-file reads never happen, or are refused
653
+
654
+ `steps` holds no `Read all of …` line, or holds one that failed:
655
+
656
+ - `… — failed: Reading all of app.log needs 41 model calls, over the limit of 30. Use search_document to narrow the question first.`
657
+ - `… — failed: app.log was already read whole for this question, and is not read whole again. …`
658
+ - `… — failed: Not run: reading all of app.log takes about … input tokens, and … are left of the … this question may use. …`
659
+
660
+ **Cause.** `analyze_whole_document` reads a file in parts, one model request each. It is offered
661
+ only for documents that are searched (a document sent whole is already in the prompt), only when
662
+ the model that explores has `generateText` (the built-in adapters do; an adapter of your own may
663
+ not), and not with `wholeDocumentAnalysis: false`. A file may take at most `maxMapChunks` parts
664
+ (30 parts of up to `mapChunkTokens`, 100,000 tokens, by default). When no searched document fits
665
+ in that (estimated from its size, with 5% to spare), the tool is not offered at all. When another
666
+ one fits, a call on the larger file fails with the `needs 41 model calls` error above. Each
667
+ document may be read whole `limits.wholeDocumentReads` times a question (1), and a read that would
668
+ pass `limits.inputTokens` or `limits.requests` is not started.
669
+
670
+ **Fix.** Ask about a part of the file, so that searches and reads answer it. Raise `maxMapChunks`
671
+ only with its cost in mind: each part is a request of up to `mapChunkTokens` input tokens.
672
+
673
+ See [Tools](./reference/tools.md) and [Costs and limits](./guides/costs-and-limits.md).
674
+
675
+ ### "Could not read any part of app.log: …"
676
+
677
+ `steps` holds, for example,
678
+ `Read all of app.log for “Summarize.” — failed: Could not read any part of app.log: The model refused the key or token it was sent (HTTP 401).`
679
+ A part that failed among parts that were read is counted in the result's `parts_that_failed`, and
680
+ its notes say `[This part could not be read: The model was busy (HTTP 429).]`.
681
+
682
+ **Cause.** The model requests of the parts failed, after their retries. Since 0.6.0 the model, the
683
+ step and `toolTurns` are told why by the error's kind, its HTTP status or its connection code, never
684
+ by its message, which can name a project, a host, a key or a URL:
685
+
686
+ | Reason | The error |
687
+ |---|---|
688
+ | `The request was larger than the model takes (HTTP 400).` | Kind `context_overflow`: a part too large for the model, even read in halves. |
689
+ | `The model's quota has run out (HTTP 429).` | Kind `quota`. |
690
+ | `The model was busy (HTTP 429).` | Kind `rate_limit`. |
691
+ | `The model took too long to answer.` | Kind `timeout`, a part read that ran past its 180 s, an `AbortSignal.timeout` of your own, or an undici headers or body timeout. |
692
+ | `The model could not be reached.` | Kind `unreachable`, or a connection code on the error or its cause (`ECONNREFUSED`, `ENOTFOUND`, `UND_ERR_SOCKET`…). |
693
+ | `The model failed on its side (HTTP 503).` | Kind `server`. |
694
+ | `The model refused the key or token it was sent (HTTP 401).` | Kind `auth`. |
695
+ | `The model refused the request (HTTP 400).` | Kind `invalid`. |
696
+ | `The model's reply could not be read (HTTP 200).` | A reply that was not JSON, such as a gateway's page. |
697
+ | `The model returned no text (SAFETY).` | A reply with no text to the package's part reader. The provider's reason is given only when it is a plain word. |
698
+ | `The model request failed.` | Any other error, such as a plain `Error` that a `generate` of your own throws. |
699
+
700
+ The HTTP status is given when the error has one. The store's own errors keep their message:
701
+ `[This part could not be read: The document store could not be read (EIO). Try again.]`.
702
+
703
+ **Fix.** Act on the kind, as for the chat requests ([Errors from the model](#errors-from-the-model)).
704
+ To see the provider's words, log them where they arrive: in the `fetch` option of the adapter, or
705
+ in a `generate` of your own. A `generate` of your own can give the model a reason by throwing an
706
+ error with a `kind` or an HTTP `status`.
707
+
708
+ See [`analyze_whole_document`](./reference/tools.md#analyze_whole_document).
709
+
710
+ ### The model repeats the same calls
711
+
712
+ `steps` holds `… — already shown above`, or the same search in other words over and over, or
713
+ `3 more tool calls in this turn were not run (at most 8 a turn)` (for one:
714
+ `1 more tool call in this turn was not run (at most 8 a turn)`).
715
+
716
+ **Cause.** A call whose result is still in the conversation in full (the same search, or a read of
717
+ lines already shown) is not run again: the model gets a pointer to the earlier result, which costs
718
+ no file access. A search in other words is a new call and runs. A model that keeps searching uses
719
+ its tool turns, and then must answer. A smaller model does this more often. Two searches in a row
720
+ that fail with an error in the same mode get a hint: for `regex`, to try `exact` or `keywords`; for
721
+ the other modes, to check the arguments. A search that finds nothing is not a failure and gets no
722
+ hint.
723
+
724
+ Some calls run again by design. With Claude's context editing (an edit `clear_tool_uses_…` or
725
+ `compact_…` in `body.context_management`), Claude may no longer have an earlier result, so no call
726
+ is answered with a pointer. A read of one line from the tool rounds of an earlier question, and an
727
+ exact or regex search that 0.5.0 stored without its last match, run again too.
728
+
729
+ **Fix.** Nothing breaks: the question still ends with an answer within `limits.toolTurns`, plus one
730
+ more request when the answer comes back without text. To cap the cost of a model that loops, lower
731
+ `limits.toolTurns`. To loop less, give the searching to a stronger model as an
732
+ [explorer](./guides/explorer-model.md), and pass the `toolTurns` of earlier questions back, so that
733
+ a follow-up starts from what was already found.
734
+
735
+ See [Conversations](./guides/conversations.md) and [`AskLimits`](./reference/ask.md#asklimits).
736
+
737
+ ## Errors from the model
738
+
739
+ A model request that fails, and is not mended by sending it again, reaches you as a
740
+ `ModelRequestError`: a `GeminiRequestError`, `OpenAiRequestError` or `AnthropicRequestError`. Its
741
+ `kind` says what went wrong, `status` is the HTTP status (0 when no answer came, the model sent
742
+ nothing for the whole wait, or a streamed reply was cut off; 200 for a reply that came and could
743
+ not be read), and its message is most often the provider's own. Log the message; show your own
744
+ words, chosen by `kind`. `partialResultOf(error)` gives what the question found and used until
745
+ then.
746
+
747
+ ### `context_overflow`: the request is larger than the model takes
748
+
749
+ The provider's message, for example Vertex AI's `The input token count exceeds the maximum number of tokens allowed 1048576.`,
750
+ with `limitTokens` and `requestedTokens` when the message gives the numbers. A body over a size
751
+ limit (HTTP 413) is this kind too. So is a request larger than the tokens a minute
752
+ (or a day) that the account allows, though it comes as HTTP 429 or 413 and its words are those of
753
+ a rate limit: OpenAI's
754
+ `Request too large for gpt-4o in organization org-… on tokens per min (TPM): Limit 30000, Requested 45237.`,
755
+ or Groq's `… on tokens per minute (TPM): Limit 6000, Requested 6438 …`. Its `limitTokens` is that
756
+ allowance. In 0.5.0, which gave errors no kind, it was sent again three times as it was.
757
+
758
+ **Cause.** The loop recovers on its own when it can: it shortens older tool results and sends the
759
+ request again (at most twice a question), or, before any tool ran, plans the documents again,
760
+ once, for a smaller window worked out from the provider's numbers (see
761
+ [How it works](./how-it-works.md#a-request-too-large-for-the-model)). A request of this kind is
762
+ never sent again as it was. `steps` then holds
763
+ `The request was larger than the model takes: older tool results were shortened, and it was sent again`
764
+ or `The first request was larger than the model's window of … tokens: the files were planned again to fit it`.
765
+ For an allowance a minute they say so:
766
+ `The request was larger than the provider allows in a minute: older tool results were shortened, and it was sent again`,
767
+ `The first request was larger than the 30,000 tokens a minute that the provider allows: the files were planned again to fit it`,
768
+ or, when the message gives no number,
769
+ `The first request was larger than the provider allows in a minute: the files were planned again for a smaller request`
770
+ (`a day` for an allowance a day). The error reaches you when that was not enough:
771
+
772
+ - **The history is too long.** The loop never shortens a question or an answer you pass.
773
+ - **The model's window is smaller than the budget says.** The budget assumes 1M tokens unless you
774
+ set `contextTokens` on the adapter or in the budget. Each question then starts with a request the
775
+ provider refuses, and plans again; when the window it plans for is still too large, the error is
776
+ thrown.
777
+ - **The model may not have its conversation rewritten.** Claude's conversation is append-only, so
778
+ old tool results are never shortened for it.
779
+ - **The body is too large for a gateway.** Set `maxRequestBytes` to its limit.
780
+ - **The account allows fewer tokens a minute than the model's window.** Every request of a
781
+ question must pass that allowance.
782
+
783
+ **Fix.** Keep the history under a limit you choose, dropping old tool rounds first, then old turns.
784
+ For a model or gateway with smaller limits, set `contextTokens` (and `maxRequestBytes`) on the
785
+ adapter (`gemini()`, `openAiCompatible()`, `anthropic()`), or with `askGemini` pass
786
+ `budget: { contextTokens, maxRequestBytes }` (or set them in the `budget` of `createLargeFiles`).
787
+ For an allowance a minute, set `contextTokens` below it, or raise the account's tier. Keep
788
+ `partialResultOf(error).toolTurns` with the conversation, and tell the user to start a new chat or
789
+ ask about fewer files.
790
+
791
+ A provider whose wording the library does not know gives kind `invalid`, and the loop does not
792
+ recover. Besides the wording of Gemini, OpenAI and Claude, it knows that of Text Generation
793
+ Inference and Together ("… tokens +
794
+ max_new_tokens must be <= 32769. Given: 40000 …"), LM Studio ("loaded with context length of only
795
+ 4096 tokens"), Amazon Bedrock ("Input is too long for requested model."), and the message at the
796
+ top of the body that vLLM before its OpenAI-shaped errors, SGLang, FastChat and servers built on
797
+ FastAPI send.
798
+ `classifyModelError(status, message)` shows how a message is read; a wrapper around your adapter
799
+ can set the kind itself ([Your own adapter and loop](./guides/own-adapter-and-loop.md)).
800
+
801
+ See [Conversations](./guides/conversations.md) and
802
+ [Errors and reliability](./guides/errors-and-reliability.md).
803
+
804
+ ### `quota` or `rate_limit`: HTTP 429
805
+
806
+ **Cause.** Too many requests or tokens for the account. The two kinds differ in one thing: a wait
807
+ mends a `rate_limit` (a quota per minute, Gemini's among them) and not a `quota`. The library sends
808
+ a `rate_limit` request again a few times, and throws a `quota` error at once. While it waits,
809
+ `onActivity` reports it: `The model did not answer (HTTP 429). Trying again in 2 s…`. A whole-file
810
+ read reaches a quota per minute first: up to 30 part reads, four at a time. Claude's HTTP 529
811
+ (overloaded) is neither: it is kind `server`.
812
+
813
+ A `quota` is a quota per day, or money: a Gemini quota per day (in the error's `details`, or named
814
+ in Vertex AI's message, `Quota exceeded for …requests_per_day…`), OpenAI's `insufficient_quota`,
815
+ HTTP 402 (DeepSeek's "Insufficient Balance", OpenRouter's "Insufficient credits"), Claude's "Your
816
+ credit balance is too low" (HTTP 400), and Claude's spending limits ("You have reached your API
817
+ usage limits", HTTP 400, or HTTP 429 with `enforced_spend_limit_reached`). 0.5.0 gave errors no
818
+ kind, and sent each of these that came as HTTP 429 again three times.
819
+
820
+ A request larger than the tokens a minute allows also comes as HTTP 429, and is
821
+ [`context_overflow`](#context_overflow-the-request-is-larger-than-the-model-takes): a wait does not
822
+ let it through.
823
+
824
+ **Fix.** For `rate_limit` under load, wait longer (`retry: { retries: 5, baseDelayMs: 2_000 }`),
825
+ raise the quota, or move the searching to an explorer on another model or project. Tell the user to
826
+ try again in a minute; `error.retryAfterMs` is the wait the provider named. A `quota` error is for
827
+ whoever runs the account: alert them, and tell the user the assistant is not available.
828
+
829
+ See [Errors and reliability](./guides/errors-and-reliability.md) for every kind and the waits,
830
+ [`RetryOptions`](./reference/errors-and-retries.md#retryoptions), and
831
+ [Gemini API and Vertex AI](./guides/vertex-and-gemini.md).
832
+
833
+ ### `timeout`: "Gemini sent nothing for 600 s."
834
+
835
+ Or `Gemini sent nothing for 300 s.`, `The model sent nothing for 600 s.` (OpenAI-compatible),
836
+ `Claude sent nothing for 600 s.`. Status 0, kind `timeout`.
837
+
838
+ **Cause.** Each adapter aborts a chat request that gets nothing for `firstByteTimeoutMs` (600 s)
839
+ before its reply starts, or for `idleTimeoutMs` (300 s) between two pieces of it. The loop sends it
840
+ again once, unless text of it was shown, so by the time you see the error the user may have waited
841
+ twice that long. What makes a model silent that long:
842
+
843
+ - a model that thinks long on a large request sends nothing while it thinks;
844
+ - a reply that is not streamed arrives whole at the end. On Gemini and OpenAI-compatible
845
+ endpoints that is an explorer's requests, every request when you pass no `onText`, every request
846
+ of `openAiCompatible({ stream: false })`, and every request to a Gemini endpoint without
847
+ `streamUrl`. `anthropic()` streams every request unless you pass `stream: false`;
848
+ - a gateway between your server and the provider holds the stream back;
849
+ - the provider hangs.
850
+
851
+ **Fix.** For a model that thinks long, raise `firstByteTimeoutMs` (an option of `askGemini`,
852
+ `gemini()`, `openAiCompatible()` and `anthropic()`; 0 waits without end), or lower its thinking. To
853
+ fail sooner, lower both waits. Bound the whole question with a `signal` that aborts at your
854
+ deadline. Part reads of a whole-file read have a limit of their own, 180 s each: a part that runs
855
+ out is tried once more, then counted in the read's `parts_that_failed`.
856
+
857
+ See [Errors and reliability](./guides/errors-and-reliability.md).
858
+
859
+ ### `unreachable`: "Gemini could not be reached (fetch failed)."
860
+
861
+ Or `The model could not be reached (…).` and `Claude could not be reached (…).`. Status 0, kind
862
+ `unreachable`.
863
+
864
+ **Cause.** No HTTP answer came: a name that does not resolve, a refused connection, a proxy that
865
+ your server must go through, a certificate that Node does not trust (a corporate proxy that
866
+ inspects TLS). The request is sent again up to 3 times before you see this. While it waits,
867
+ `onActivity` says `The model could not be reached. Trying again…`.
868
+
869
+ The same kind comes for a reply that began and was cut off on its way: a connection that broke
870
+ while the reply arrived, a stream that closed before its end (an empty one too, see
871
+ ["Gemini's reply ended before it was complete."](#geminis-reply-ended-before-it-was-complete)),
872
+ and a reply of HTTP 200 whose body was empty and not of type `text/event-stream`
873
+ (`Gemini could not be reached (the reply was empty).`, `The model could not be reached (the reply was empty).`,
874
+ `Claude could not be reached (the reply was empty).`). These are sent again too, unless text of
875
+ the reply was shown, and `onActivity` says
876
+ `The model's reply was cut off on its way. Trying again…`.
877
+
878
+ **Fix.** Log `error.cause`: it is the error of `fetch`, whose own `cause` usually names the system
879
+ error (`ENOTFOUND`, `ECONNREFUSED`, a certificate error). Node's `fetch` does not go through a proxy
880
+ unless it is set up to: every adapter and `askGemini` take a `fetch` option for one that does. A
881
+ corporate certificate authority is added with the `NODE_EXTRA_CA_CERTS` environment variable.
882
+
883
+ See [Errors and reliability](./guides/errors-and-reliability.md).
884
+
885
+ ### `auth`: Vertex AI refuses the token
886
+
887
+ HTTP 401 or 403, kind `auth`, with Google's message. It is not sent again.
888
+
889
+ **Cause.**
890
+
891
+ - **401**: the access token expired or is not one. A string given as `accessToken` is sent as it is
892
+ for as long as the endpoint lives, and an access token expires after an hour by default: the
893
+ first questions work, the later ones fail.
894
+ - **403**: the identity has no role that may call the model (Vertex AI User,
895
+ `roles/aiplatform.user`), the Vertex AI API is not enabled in the project, or the project is not
896
+ the one you meant.
897
+ - On the Gemini API, a key that is not valid comes as HTTP 400 and is kind `auth` too.
898
+
899
+ **Fix.** Give `vertexAi()` a function as `accessToken`. It is called before every request, part
900
+ reads included:
901
+
902
+ ```ts
903
+ import { GoogleAuth } from "google-auth-library";
904
+ import { vertexAi } from "llm-large-files/gemini";
905
+
906
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
907
+
908
+ export const endpoint = vertexAi({
909
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
910
+ location: "global",
911
+ model: "gemini-3.8-flash",
912
+ // GoogleAuth keeps the token and renews it before it expires.
913
+ accessToken: async () => {
914
+ const token = await auth.getAccessToken();
915
+ if (!token) throw new Error("No access token from the application default credentials.");
916
+ return token;
917
+ },
918
+ });
919
+ ```
920
+
921
+ For a 403, check which identity the server runs as, give it the role, and enable the API in the
922
+ project.
923
+
924
+ An error thrown by your `accessToken` function (such as google-auth-library's "Could not load the
925
+ default credentials…") is not a `ModelRequestError`: it has no status and no kind. In a chat
926
+ request it ends the question, without a retry. The application default credentials are missing
927
+ where the server runs.
928
+
929
+ See [Gemini API and Vertex AI](./guides/vertex-and-gemini.md).
930
+
931
+ ### Azure OpenAI refuses `max_tokens`
932
+
933
+ HTTP 400, kind `invalid`, with a message such as
934
+ "Unsupported parameter: 'max_tokens' … Use 'max_completion_tokens' instead". The
935
+ `OpenAiRequestError` has `param` `"max_tokens"` when the server names the field.
936
+
937
+ **Cause.** Reasoning deployments on Azure OpenAI (and OpenAI's newer models) take
938
+ `max_completion_tokens`, not `max_tokens`. The adapter sends no output limit in a chat request: one
939
+ there comes from your `body`. In the part reads of a whole-file read it chooses the name from the
940
+ URL (`max_completion_tokens` on Azure OpenAI's hosts) and, when a server refuses the name it was
941
+ sent, switches to the other. A gateway on another host gets `max_tokens` first, and one that
942
+ rewrites the error leaves the adapter nothing to learn from.
943
+
944
+ **Fix.** Put `max_completion_tokens` in `body`, and behind a gateway set `maxTokensField`:
945
+
946
+ ```ts
947
+ import { openAiCompatible } from "llm-large-files/openai";
948
+
949
+ export const azure = openAiCompatible({
950
+ // https://<resource>.openai.azure.com/openai/deployments/<deployment>/chat/completions?api-version=<version>
951
+ url: process.env.AZURE_OPENAI_CHAT_URL!,
952
+ headers: { "api-key": process.env.AZURE_OPENAI_API_KEY! },
953
+ model: process.env.AZURE_OPENAI_DEPLOYMENT!,
954
+ body: { max_completion_tokens: 16_000 }, // not max_tokens
955
+ maxTokensField: "max_completion_tokens", // the name in part reads, whatever the host
956
+ });
957
+ ```
958
+
959
+ See [OpenAI-compatible endpoints](./guides/openai-compatible.md).
960
+
961
+ ### `invalid`: HTTP 400 or 404 for a setting
962
+
963
+ **Cause.** The provider refused the request as it was, and sending it again would not help. The
964
+ usual ones:
965
+
966
+ - **A setting one model does not take.** With an explorer, both models get your `generationConfig`
967
+ unless you give `explorerGenerationConfig`. Given a `thinkingLevel`, `gemini-2.5-flash-lite` on
968
+ Vertex AI answered HTTP 400 "thinking_level is not supported by this model".
969
+ - **A model the location does not serve, or a wrong model name** (HTTP 404).
970
+ - **A server that does not know `tool_choice`.** The request that must be answered in text sends
971
+ `tool_choice: "none"`, so a question fails when it needs that request: always with an explorer,
972
+ and when the tool turns run out.
973
+ - **A server that cannot stream** and refuses the streamed request.
974
+
975
+ **Fix.** Give the explorer its own `explorerGenerationConfig`. Check the model name and location.
976
+ For an OpenAI-compatible server, set `answerWithoutTools: "omit"` or `stream: false`.
977
+
978
+ See [An explorer model](./guides/explorer-model.md) and
979
+ [OpenAI-compatible endpoints](./guides/openai-compatible.md).
980
+
981
+ ### "Gemini's reply could not be read: it was not JSON (text/html)."
982
+
983
+ The whole message: `Gemini's reply could not be read: it was not JSON (text/html). A proxy or gateway may have answered in its place.`
984
+ From the other adapters it starts `The model's reply could not be read` (OpenAI-compatible) or
985
+ `Claude's reply could not be read`. The brackets hold the media type of the response, and are left
986
+ out when it has none. Status 200 (the status of the response), kind `invalid`, and the
987
+ `SyntaxError` of `JSON.parse` as `cause`.
988
+
989
+ **Cause.** A reply came with HTTP 200, but its body was not JSON: a gateway, a proxy or a sign-in
990
+ page answered with HTML. So does a reply asked for as a stream whose body starts like neither
991
+ events nor JSON. It is not sent again: the same page would most likely come back. In a whole-file
992
+ read, the part is told `The model's reply could not be read (HTTP 200).`
993
+
994
+ In 0.5.0 this was the `SyntaxError` itself, with no `status`, and a streamed Gemini request that
995
+ got such a page came back as an empty reply. A test of
996
+ `error instanceof SyntaxError` no longer matches: test `error.cause instanceof SyntaxError`. Kind
997
+ `invalid` alone also covers every other request that the provider refused.
998
+
999
+ **Fix.** Call the URL the way the adapter does and look at what comes back. Fix the gateway's route
1000
+ or its sign-in, or give the adapter the URL that answers JSON.
1001
+
1002
+ See [Errors and reliability](./guides/errors-and-reliability.md).
1003
+
1004
+ ## Performance and cost
1005
+
1006
+ ### Costs are higher than expected
1007
+
1008
+ Look at `result.usage`: `inputTokens`, `cachedInputTokens` (read from the provider's prompt cache),
1009
+ `outputTokens` (thoughts included), `thoughtTokens`, `requests`, and the same for each model in
1010
+ `byModel`.
1011
+
1012
+ **Cause.** What costs most:
1013
+
1014
+ - **Whole-file reads.** One read is up to `maxMapChunks` (30) part requests of up to
1015
+ `mapChunkTokens` (100,000) tokens: up to 3M input tokens.
1016
+ - **Documents sent whole, in a tool loop.** Every request of a question carries the documents that
1017
+ went in whole, up to `inlineTokens` (200,000 tokens), and a question makes up to
1018
+ `limits.toolTurns` (12) chat requests. A prompt cache makes the repeats cheaper:
1019
+ `cachedInputTokens` shows how much it served.
1020
+ - **Pages.** A page shown to the model costs about 530 tokens on Gemini (3,500 by default for
1021
+ Claude), and stays in every later request of the question. With `keepOriginals: ["pdf"]`, a
1022
+ question about a PDF sent whole can take several requests, because `view_pages` is offered for it.
1023
+ - **Thinking.** Thoughts are billed as output.
1024
+ - **`documentPlacement: "last"`.** The documents then move to the latest turn, and a prompt cache
1025
+ cannot reuse them: keep the default, `"first"`.
1026
+ - **The first request of a follow-up question.** The tool rounds of an earlier question are sent
1027
+ again without their `tool_turns_left` (since 0.6.0), so that request reads the cache only up to
1028
+ the tool rounds of the question before it: the documents, the cards and the turns before those
1029
+ rounds still hit. The later requests of the question hit as before.
1030
+ - **The first request after the upgrade to 0.6.0.** The tool guide, the descriptions of
1031
+ `search_document` and `analyze_whole_document`, and the frame of every file sent whole changed,
1032
+ so the first request of each conversation reads from the cache at most what comes before the
1033
+ first text that changed. For a question with files to search, that is nothing on Claude and
1034
+ OpenAI-compatible endpoints, where the tools come first, and at most your own system text on
1035
+ Gemini, where the tool guide follows it in the system instruction. For a question whose files
1036
+ are all sent whole, it is your own system text, and `view_pages` with its guide when the pages of
1037
+ a PDF can be looked at. With Claude's `cache_control`, that request is a cache write.
1038
+ While servers of both versions answer the same conversations, each switch misses again.
1039
+
1040
+ **Fix.** Set ceilings for one question, and log the usage per user or session:
1041
+
1042
+ ```ts
1043
+ import { askGemini } from "llm-large-files/gemini";
1044
+
1045
+ const result = await askGemini({
1046
+ files, endpoint, documentIds, messages, owner,
1047
+ limits: {
1048
+ inputTokens: 1_000_000, // no more tools once the question has sent this many input tokens
1049
+ requests: 20, // chat requests and part reads together
1050
+ wholeDocumentReads: 0, // no whole-file reads
1051
+ },
1052
+ });
1053
+
1054
+ const { inputTokens, cachedInputTokens, outputTokens, requests, byModel } = result.usage;
1055
+ console.log({ owner, inputTokens, cachedInputTokens, outputTokens, requests, byModel });
1056
+ ```
1057
+
1058
+ The ceilings are checked before each request that may use tools. Once one is reached, the next
1059
+ request is the answer, which is still made: a question can pass `inputTokens` by about two
1060
+ requests (the one that crossed it, and the answer): set it that far below what must not be passed
1061
+ ([Costs and limits](./guides/costs-and-limits.md#inputtokens-and-requests-are-checked-between-turns)). A
1062
+ cheaper [explorer model](./guides/explorer-model.md) takes the searching and the part reads off the
1063
+ model that answers.
1064
+
1065
+ See [Costs and limits](./guides/costs-and-limits.md) and [`AskLimits`](./reference/ask.md#asklimits).
1066
+
1067
+ ### Every follow-up question searches again
1068
+
1069
+ **Cause.** The tool results of a question are in its result (`toolTurns`), not in the library. A
1070
+ follow-up whose `messages` hold only the text of earlier turns has none of them.
1071
+
1072
+ **Fix.** Keep `result.toolTurns` with the conversation, and pass them back between the question
1073
+ they belong to and its answer. A follow-up then gets a pointer to an earlier result instead of
1074
+ running the same call again. With Claude's context editing, calls run again all the same (see
1075
+ [above](#the-model-repeats-the-same-calls)).
1076
+
1077
+ See [Conversations](./guides/conversations.md).
1078
+
1079
+ ### A question takes minutes
1080
+
1081
+ **Cause.** A question makes up to `limits.toolTurns` (12) chat requests, one after another. A model
1082
+ that thinks takes long on each; a whole-file read adds its part reads, four at a time, each up to
1083
+ 180 s; a request that failed waits before it is sent again (up to `retry.maxDelayMs`, 60 s, when
1084
+ the provider asks); a silent model is waited for 600 s, twice. Nothing streams while an explorer
1085
+ works.
1086
+
1087
+ **Fix.** Show `onActivity` to the user: it says what the question is doing
1088
+ (`Search app.log (exact) for “timeout”…`, `Writing the answer…`, and each retry). The events of
1089
+ `askStream` or `onEvent` say more: each tool call, the parts of a whole-file read, and the retries
1090
+ of its requests ([events](./reference/events.md)). Bound the time
1091
+ with a `signal` that aborts at your deadline. Lower `limits.toolTurns`, turn off whole-file reads,
1092
+ or use a faster model as the explorer.
1093
+
1094
+ See [Errors and reliability](./guides/errors-and-reliability.md) and [Web app](./guides/web-app.md).
1095
+
1096
+ ### Memory grows with large files or many users
1097
+
1098
+ **Cause.**
1099
+
1100
+ - Each library (each `createLargeFiles` call) keeps documents ready for repeated tool calls, up to
1101
+ `cacheBytes` (256 MB). Several libraries in one process, such as one per chat, each have their
1102
+ own.
1103
+ - A document larger than `wholeDocumentBytes` (2 MB) is read by range only when the store has
1104
+ `readTextRange`, as `FileDocumentStore` does. With a store of your own without it, and with
1105
+ `MemoryDocumentStore`, every document is loaded whole.
1106
+ - An upload is held in memory whole while it is read and extracted, with several copies of its
1107
+ text, and the parsers of PDF, DOCX, PPTX and XLSX take memory of their own while they read, in
1108
+ the same heap as everything else, unless they run in the child processes of
1109
+ `createIsolatedExtractors`.
1110
+ - `@cantoo/pdf-lib`, which reads PDFs for the page check, the picture marks and `view_pages`,
1111
+ keeps every name and every reference it has read for the life of the process. Real PDFs add
1112
+ little, as they share most of them, but each crafted one with other names or object numbers adds
1113
+ its own, and it never comes back: 2 MB of different names kept 37 MB, and files of 9 KB that each
1114
+ declared a million new objects kept about 140 MB each, until the fourth ingest ran a heap of
1115
+ 512 MB out of memory, or the seventh look a heap of 1 GB. On the server that answers `view_pages`,
1116
+ it comes back only when that server restarts.
1117
+
1118
+ **Fix.** Give a store of your own `readTextRange` (and `putIndex` and `getIndex`, so that no pass
1119
+ over the text is needed first). Lower `cacheBytes` and `maxConcurrentScans` to fit the memory of
1120
+ the server, and `maxUploadBytes` and `maxTextBytes` to the files you expect. To keep a file that
1121
+ needs too much memory from stopping the server, read it in a process of its own with its own heap
1122
+ limit, as `createIsolatedExtractors` does: a worker thread does not keep it apart. Its children,
1123
+ replaced after 50 files, also give back what `@cantoo/pdf-lib` kept, and so does a process for each
1124
+ ingest when it ends. For the documents of users you do not trust, do not offer
1125
+ `view_pages` (`viewPages: false`), or keep no PDF originals.
1126
+
1127
+ See [Storage](./guides/storage.md) and [Deployment](./guides/deployment.md#uploads-and-ingest).
1128
+
1129
+ ### Other requests are slow while a question searches
1130
+
1131
+ **Cause.** A regex search runs on the server's event loop, in slices of up to 250 ms. One search
1132
+ stops after 3 s, and the regex searches of one question share 6 s (`REGEX_BUDGET_MS`); a pattern
1133
+ with a nested quantifier, such as `(a+)+`, is refused before it runs. So the model's patterns can
1134
+ hold up other requests of the same process for up to a quarter of a second at a time.
1135
+
1136
+ **Fix.** Run several server processes, so that one busy process does not hold up the others. In a
1137
+ tool loop of your own, `regexBudgetMs` of `files.tools()` lowers the shared time.
1138
+
1139
+ See [Security](./security.md) and [Tools](./reference/tools.md).
1140
+
1141
+ ## Storage and several servers
1142
+
1143
+ ### `DocumentStoreError`: "The document store could not be read (EIO). Try again."
1144
+
1145
+ Thrown by a question, `files.getMeta`, `files.getOriginal`, and by `files.delete` when the look-up
1146
+ fails (a failure of the store's own `delete` comes as the store's error). When the error behind it
1147
+ has no `code`, the message has none. Inside a question's tool call, the model gets it as the
1148
+ call's error, and `steps` shows
1149
+ `… — failed: The document store could not be read (EIO). Try again.`. The upload
1150
+ handler's `get` and `remove` answer `500` with `The file could not be looked up (EIO).` or
1151
+ `The file could not be deleted (EIO).`.
1152
+
1153
+ **Cause.** The store failed while it was read: a network volume that did not answer, too many open
1154
+ files, a database that is down. The documents are not gone.
1155
+
1156
+ **Fix.** Show the message (it names no path and no host) and let the user try again; do not ask
1157
+ them to upload again. Log `error.cause`, the store's own error, and `error.code`. Fix the storage.
1158
+
1159
+ See [`DocumentStoreError`](./reference/library.md#documentstoreerror) and
1160
+ [Storage](./guides/storage.md).
1161
+
1162
+ ### Documents are found on one server and missing on another
1163
+
1164
+ `DocumentsNotFoundError` for documents that were just uploaded, on some requests and not others, or
1165
+ for every document after a restart.
1166
+
1167
+ **Cause.** The servers do not share the store: a `MemoryDocumentStore` (each process has its own,
1168
+ and loses it when it stops), or a `FileDocumentStore` on each server's local disk.
1169
+
1170
+ **Fix.** Use one store that every server reads: `FileDocumentStore` on a shared volume, or a store
1171
+ of your own on shared storage. The library keeps nothing else between requests that another server
1172
+ would need.
1173
+
1174
+ See [Deployment](./guides/deployment.md) and [Storage](./guides/storage.md).
1175
+
1176
+ ### A store outage shows up as expired documents
1177
+
1178
+ Users are told to upload files again while your database is down.
1179
+
1180
+ **Cause.** A store of your own returns `undefined` when its read fails. `undefined` means "this
1181
+ document does not exist", so the library reports the documents as missing.
1182
+
1183
+ **Fix.** Return `undefined` only for a document that is not there or has expired, and let every
1184
+ other failure throw. The library turns a thrown error into a `DocumentStoreError`, which says to
1185
+ try again.
1186
+
1187
+ See [Storage](./guides/storage.md) and [`DocumentStore`](./reference/library.md#documentstore).
1188
+
1189
+ ### `500`: "Upload failed.", or `422` with your database's message
1190
+
1191
+ **Cause.** A store write that fails is thrown as it came, not as a `DocumentStoreError`. The upload
1192
+ handler answers it `500` with `{ "error": "Upload failed." }` when it has no `status` (or
1193
+ `statusCode`) from 400 to 599 and is not a Node system error with `code` and `syscall`. Its message
1194
+ is your database's own and may name its host, so it is not sent, and the handlers log nothing.
1195
+
1196
+ Two paths answer it `422` with your database's message instead, as a file that cannot be read: an
1197
+ `ingest` of your own that throws a new error in its place, as `ingestInProcess` in
1198
+ [Deployment](./guides/deployment.md#uploads-and-ingest) does, and a route of your own, as in
1199
+ [Web app](./guides/web-app.md#filesingest-and-its-errors). Every case is in the
1200
+ [node reference](./reference/node.md#uploadrequest-response).
1201
+
1202
+ **Fix.** In a store of your own, log a write that fails, and throw an error with a `status` (a
1203
+ `503`, say) whose message is fit for a user. An `ingest` of your own must copy that status, and a
1204
+ system error's `code` and `syscall`, onto the error it throws, as `ingestInProcess` in
1205
+ [Deployment](./guides/deployment.md#uploads-and-ingest) does.
1206
+
1207
+ See [Storage](./guides/storage.md) and [`llm-large-files/node` reference](./reference/node.md).
1208
+
1209
+ ### `500`: "Upload failed (ENOSPC)."
1210
+
1211
+ **Cause.** The disk of a `FileDocumentStore` is full. Expired documents are removed when they are
1212
+ next looked up, or by `files.sweep()`: one that nobody asks for again stays on disk until a sweep.
1213
+ Kept originals (`keepOriginals`) take space up to the upload limit each, until they expire.
1214
+
1215
+ **Fix.** Run `files.sweep()` on a timer. It also removes files that belong to no document (an
1216
+ upload that failed) once they are an hour old.
1217
+
1218
+ ```ts
1219
+ // `files` from createLargeFiles.
1220
+ setInterval(() => {
1221
+ files.sweep().then(
1222
+ (removed) => console.log(`sweep removed ${removed} expired documents`),
1223
+ (error: unknown) => console.error("sweep failed", error),
1224
+ );
1225
+ }, 60 * 60 * 1000).unref();
1226
+ ```
1227
+
1228
+ Lower `ttlMs` if documents need not live 72 hours.
1229
+
1230
+ See [Deployment](./guides/deployment.md) and [Storage](./guides/storage.md).
1231
+
1232
+ ## Streaming
1233
+
1234
+ ### The answer arrives in one piece
1235
+
1236
+ **Cause.** Text streams only when the loop asks for it as it is written (`streamText`, on by
1237
+ default with `onText` and in `askStream`) and the adapter can stream:
1238
+
1239
+ - `askGemini` and `gemini()` stream only to an endpoint with a `streamUrl`. `geminiApi()` and
1240
+ `vertexAi()` set it; an endpoint you write for a gateway may not.
1241
+ - `openAiCompatible({ stream: false })` and `anthropic({ stream: false })` do not stream, and a
1242
+ server that answers a streamed request in one piece, with JSON, is read whole. `onText` is then
1243
+ called once, with the whole text. (A reply that starts like events is read as a stream, whatever
1244
+ its content type.)
1245
+ - With an explorer, nothing streams until the answering model starts.
1246
+ - A proxy or a compression middleware between your server and the browser holds the events back.
1247
+
1248
+ **Fix.** Give a gateway endpoint its stream URL:
1249
+
1250
+ ```ts
1251
+ import { askGemini, type GeminiEndpoint } from "llm-large-files/gemini";
1252
+
1253
+ const model = `${process.env.LLM_GATEWAY_URL}/v1/models/gemini-3.8-flash`;
1254
+ const endpoint: GeminiEndpoint = {
1255
+ url: `${model}:generateContent`,
1256
+ streamUrl: `${model}:streamGenerateContent?alt=sse`, // without it, the answer arrives in one piece
1257
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.LLM_GATEWAY_TOKEN}` },
1258
+ };
1259
+
1260
+ await askGemini({ files, endpoint, documentIds, messages, owner, onText: (delta) => process.stdout.write(delta) });
1261
+ ```
1262
+
1263
+ On the way to the browser, send `X-Accel-Buffering: no` for nginx and leave the route out of
1264
+ compression.
1265
+
1266
+ See [Web app](./guides/web-app.md).
1267
+
1268
+ ### `text` events come in one piece, at the end of each reply
1269
+
1270
+ You listen with `onEvent`, and the `text` events of the answer arrive all at once, after the
1271
+ model has finished writing.
1272
+
1273
+ **Cause.** A listener of the events alone does not change how the model is asked: without `onText`,
1274
+ `streamText` is `false`, and each reply's text comes in one `text` event once the reply is in.
1275
+ `askStream` turns it on for you.
1276
+
1277
+ **Fix.** Pass `streamText: true` (or use `askStream`):
1278
+
1279
+ ```ts
1280
+ import { askWithFiles, type AskEvent } from "llm-large-files";
1281
+
1282
+ // files, model, documentIds and messages are those of your question; send() is your own.
1283
+ declare function send(event: AskEvent): void;
1284
+ await askWithFiles({ files, model, documentIds, messages, streamText: true, onEvent: send });
1285
+ ```
1286
+
1287
+ With it, a reply that fails after its first text is not sent again: the question throws, with what
1288
+ was shown. With `streamText: false`, such a reply is sent again, but the user waits longer for the
1289
+ first word, and the whole reply must arrive within the adapter's `firstByteTimeoutMs`. See
1290
+ [Errors, retries and streams](./reference/errors-and-retries.md#retries-in-events).
1291
+
1292
+ ### The events stop when the user leaves the page
1293
+
1294
+ `writeSseEvents` returns before `run.finish`, and the question ends with an `AbortError`: "The
1295
+ events stopped being read."
1296
+
1297
+ **Cause.** This is expected. When the client goes away, `writeSseEvents` stops reading and ends
1298
+ the iterator, and leaving an `askStream` (or an `eventStream`) early stops its question, so nothing
1299
+ more is paid for. `await stream.result` then rejects with the abort, and `partialResultOf(error)`
1300
+ gives what the question found until then.
1301
+
1302
+ When the question goes on instead, you passed a generator that wraps the stream: it stops only when
1303
+ it next yields, and a question waiting on a long model request goes on until then. Pass the stream
1304
+ itself, and change what is sent with `map` (return `undefined` to skip an event); or stop it
1305
+ yourself:
1306
+
1307
+ ```ts
1308
+ import type { ServerResponse } from "node:http";
1309
+ import { askStream, type AskOptions } from "llm-large-files";
1310
+ import { sseMessageOf, writeSseEvents } from "llm-large-files/node";
1311
+
1312
+ export async function answer(response: ServerResponse, options: AskOptions) {
1313
+ const stream = askStream(options);
1314
+ // Notices the page does not show are skipped; every other event is sent as sseMessageOf sends it.
1315
+ await writeSseEvents(response, stream, {
1316
+ map: (event) => (event.type === "notice" && event.display === "none" ? undefined : sseMessageOf(event)),
1317
+ });
1318
+ }
1319
+ ```
1320
+
1321
+ See [`askStream`](./reference/ask.md#askstreamoptions) and
1322
+ [when the client goes away](./reference/node.md#when-the-client-goes-away).
1323
+
1324
+ ### The stream to the browser stops or stalls
1325
+
1326
+ The browser's stream ends without your final event, or the events arrive all at once at the end.
1327
+
1328
+ **Cause.** A proxy or load balancer in front of your server closes a response on which nothing
1329
+ arrived for a while, or ends one that runs longer than its limit, or buffers the events. A question
1330
+ can be silent for minutes: an explorer at work, a model that thinks, a whole-file read.
1331
+
1332
+ **Fix.** Write an SSE comment line (`: keep-alive`) every 15 seconds or so, turn off buffering for
1333
+ the route, and set the proxy's timeout above your own deadline for a question. `writeSseEvents`
1334
+ sends the comment every 15 seconds and `X-Accel-Buffering: no` for you.
1335
+
1336
+ See [Web app](./guides/web-app.md) and [Deployment](./guides/deployment.md).
1337
+
1338
+ ### "Gemini's reply ended before it was complete."
1339
+
1340
+ Or `The model's reply ended before it was complete.` and `Claude's reply ended before it was complete.`.
1341
+ Status 0, kind `unreachable`.
1342
+
1343
+ **Cause.** A streamed reply closed without the event that says why it ended: a proxy or gateway
1344
+ between your server and the provider cut it. The request is sent again when none of its text was
1345
+ shown, and `onActivity` says `The model's reply was cut off on its way. Trying again…`. When some
1346
+ text was shown, it cannot be taken back, and the error reaches you after the user saw part of an
1347
+ answer.
1348
+
1349
+ Two kinds of reply are not cut off, and are read whole. A Gemini stream URL that a gateway answers
1350
+ in one piece (a JSON array of chunks, as Gemini sends without `?alt=sse`) is read as one reply;
1351
+ 0.5.0 read it as an empty reply. A stream that said it is whole (`[DONE]`, Claude's
1352
+ `message_stop`) and was then left open, or broke, keeps its reply: the body is read for one more
1353
+ second at most, and then closed; 0.5.0 waited for such a connection to close, and failed the
1354
+ request when it broke, as a model that could not be reached.
1355
+
1356
+ **Fix.** Keep the text that was shown and mark it as cut off, and keep `partialResultOf(error)`'s
1357
+ `toolTurns` so that the user's next question starts from what was found. Raise the gateway's
1358
+ timeouts for streams, or route the stream URL past it.
1359
+
1360
+ See [Errors and reliability](./guides/errors-and-reliability.md).
1361
+
1362
+ ### "The model's reply could not be read: an event of its stream held more than 64,000,000 characters."
1363
+
1364
+ Or `Gemini's reply could not be read: …` and `Claude's reply could not be read: …`. Status 200 (the
1365
+ status of the response), kind `invalid`.
1366
+
1367
+ **Cause.** One event of the streamed reply held more than 64,000,000 characters: a server or a
1368
+ gateway that never ended an event, or sent data lines without the blank line that ends one. It is
1369
+ not sent again: the same stream would most likely come back. In 0.5.0 nothing capped an event: it
1370
+ grew one string, read again from its start with each piece that came, so the read slowed with the
1371
+ square of its size. One event of 32 MB, in pieces of 16 KB, took 12.5 to 13.5 s on Node 24 on
1372
+ Windows ([Measurements](./measurements.md#the-server)). Data lines without an end grew the same
1373
+ string.
1374
+
1375
+ **Fix.** Look at the stream the server or the gateway sends: an answer of a model fits well within
1376
+ the limit.
1377
+
1378
+ See [`parseSseJson`](./reference/errors-and-retries.md#parsessejsonstream-hooks).
1379
+
1380
+ ### The question goes on after the user leaves
1381
+
1382
+ The model keeps working, and billing, after the user closed the tab or pressed Stop.
1383
+
1384
+ **Cause.** A question stops only when its `signal` aborts.
1385
+
1386
+ **Fix.** Abort it when the response closes:
1387
+
1388
+ ```ts
1389
+ import type { ServerResponse } from "node:http";
1390
+ import { askGemini } from "llm-large-files/gemini";
1391
+
1392
+ export async function answer(response: ServerResponse) {
1393
+ const userLeft = new AbortController();
1394
+ // The response's close, not the request's: the request closes once its body has been read.
1395
+ response.on("close", () => userLeft.abort());
1396
+ return askGemini({ files, endpoint, documentIds, messages, owner, signal: userLeft.signal });
1397
+ }
1398
+ ```
1399
+
1400
+ The question then throws the signal's reason, at once: since 0.6.0 also with an adapter of your own
1401
+ that does not stop its request, and when the adapter fails with its own error as it stops. Nothing
1402
+ is sent after that, and text that arrives later is not shown. What it used until then was paid for:
1403
+ `partialResultOf(error)` gives its `usage` when the reason is an object, so abort with no reason or
1404
+ with an `Error`. Questions stopped by one shared signal all throw its one reason, and since 0.7.1
1405
+ `partialResultOf` gives none of them a result for it: give each question a controller of its own,
1406
+ or read `partial` from each question's `run.error` event (see
1407
+ [`partialResultOf`](./reference/ask.md#partialresultoferror)). A request still running when the question stopped may be billed by the provider,
1408
+ and is not counted there: pass the signal on to the request, as the built-in adapters do.
1409
+
1410
+ See [Web app](./guides/web-app.md).