llm-large-files 0.5.0 → 0.7.0

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