llm-large-files 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  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 +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
package/CHANGELOG.md CHANGED
@@ -1,353 +1,1415 @@
1
1
  # Changelog
2
2
 
3
- All notable changes to this package are recorded here. The format follows
4
- [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
- [semantic versioning](https://semver.org).
3
+ What changed in each version of `llm-large-files`, for the developers who use it. Each version
4
+ says what you need to change when you upgrade, what you can add, what works differently, and what
5
+ was fixed. Versions follow [semantic versioning](https://semver.org). While the version is 0.x, a
6
+ minor version (0.5 to 0.6) may need changes in your code or settings, and a patch (0.6.0 to 0.6.1)
7
+ does not. The **Upgrading** part of each version says what to change, and it is there even when
8
+ the answer is "nothing".
6
9
 
7
- ## [0.4.1] - 2026-11-13
10
+ <!--
11
+ Template of an entry, for maintainers. Put the newest version first.
8
12
 
9
- Fixes from a review of 0.4.0. Nothing to change in your code. Tool results are those of 0.4.0
10
- except for the three points under Changed (compared call by call with 0.3.6 over 40 documents).
13
+ ## X.Y.Z — not released yet
14
+ (At release, the date replaces "not released yet": ## X.Y.Z — YYYY-MM-DD.)
11
15
 
12
- ### Fixed
16
+ Two to four sentences: what this version is about.
17
+
18
+ ### Upgrading: what you need to change
19
+
20
+ Always present. First, whether code written for the previous version compiles as it is (check
21
+ the diff of the public .d.ts files). Then each behavior difference an app may need to act on:
22
+ what changed, who it affects, and what to do. Write "Nothing." when there is none.
23
+
24
+ ### New: what you can add
13
25
 
14
- - **A whole-file read returned almost nothing on a model that thinks.** Such a model counts its
15
- thoughts in `maxOutputTokens`. Asked for 4,096 tokens of notes on a part of a log, Gemini 3.8
16
- Flash spent 3,931 of them thinking and wrote 317 characters, and Gemini 4 Hydrogen wrote none.
17
- `createGeminiGenerateText` now sends such a request once more with 32,768
18
- (`THINKING_OUTPUT_TOKENS`), and starts there for every later request to that model: one request
19
- is wasted per model and process, not one per part. A model or a gateway that refuses the larger
20
- limit is not asked for it again. An `analysisConfig` of your own still decides what it sets.
21
- Checked live: both models then returned whole notes, and an answer that cited all 70 matching
22
- lines of a log read in three parts.
23
- - **`sweep` deleted a healthy document when one read of its metadata failed.** Every error counted
24
- as "cannot be read", and a file older than an hour was then removed, with its text and its
25
- original. Now only metadata that is not valid is that. A read that failed (a busy volume, too
26
- many open files) leaves the document alone, and a document that cannot be removed no longer
27
- stops the sweep.
28
- - **A store that could not be read looked like a deleted document.** `FileDocumentStore` answered
29
- every failed read with "not there", and `askGemini` then told the user to upload the file
30
- again. A failed read is now a `DocumentStoreError`: retry the call. Its message names no path
31
- and no host, and the error that was caught is its `cause`.
32
- - **Storage errors reached the model, and a user's screen, with the server's path.** A tool call
33
- that met `EACCES: permission denied, open '/data/large-files/doc_….txt'` passed that on in its
34
- result and in `steps`. It now answers `The document store could not be read (EACCES). Try again.`
35
- - **One model turn could hold the server.** A regex that the quick check lets through, such as
36
- `(a|a)+$`, ran for its full 3 seconds on the main thread, and a turn can hold any number of
37
- calls: five such searches in one turn answered no other request for 15 seconds. A file can ask
38
- a model for exactly that. Now:
39
- - a regex scan runs in slices of 250 ms with other work in between, and stops at a line that
40
- takes two whole slices: 0.8 s for such a search, not 3;
41
- - the regex searches of one tool set (one question, in `askGemini`) share 6 seconds
42
- (`regexBudgetMs`). Past that, a regex search answers with an error that tells the model to
43
- search another way;
44
- - `askGemini` runs at most 8 tool calls of one turn (`maxToolCallsPerTurn`). The others are
45
- answered "not run, send it again if you still need it". Sixty reads in one turn built a
46
- request of 339,000 tokens before.
47
- - **`ttlMs: Infinity` made every ingest throw** (`RangeError: Invalid time value`). It now keeps
48
- documents until they are deleted: their `expiresAt` is `NEVER_EXPIRES`.
49
- - **A long line of emoji lost characters when it was wrapped.** The cut at 2,000 could fall
50
- between the two halves of a character outside the basic plane, and each half was stored as a
51
- replacement character.
52
- - **`jsonBytes` and the planner under-counted** text with quotes, backslashes, tabs or many line
53
- breaks: by 23% for a JSON-lines export and 31% for TSV. They now count what JSON adds exactly,
54
- `DocumentMeta.jsonBytes` keeps it for planning, and `read_document` trims its result to the
55
- limit as it is sent: a read of quoted text came out at 42,514 characters against 24,000.
56
- - **`**NOTHING RELEVANT**` counted as a relevant part** of a whole-file read. The reply of a part
57
- that found nothing is recognised whatever Markdown is around it.
58
- - **A merge of notes that failed twice lost the notes of every part.** They now go on unmerged,
59
- and the answer is written from them.
60
- - **`cacheSize` counted the pieces kept of a document that is read by range**, so with a small
61
- value a document pushed itself out of memory on every search. It counts documents again.
62
- - **`delete` could leave a document listed without its text.** The metadata is removed first, and
63
- if that fails nothing else is removed.
64
- - **`\p{L}` matched nothing in a regex search.** Patterns are compiled with the Unicode flag when
65
- they allow it, and without it otherwise.
66
-
67
- ### Changed
68
-
69
- - **A file too large for `analyze_whole_document` is no longer offered it.** Its card says "It is
70
- too large to be analyzed whole", the tool guide and the declared tools leave the tool out when
71
- no file can use it, and `get_document_overview` says so in `whole_document_analysis`. A call of
72
- the tool still answers with the reason.
73
- - **`get_document_overview` works out the number of parts from the metadata**, not by reading
74
- the whole file: that took 60 MB of reads and 0.7 s for a 60 MB log. The number is the count, or
75
- within a few percent of it.
76
- - In a regex, `.` and a quantifier take a character outside the basic plane (an emoji) as one
77
- character.
78
-
79
- ### Added
80
-
81
- - `DocumentStoreError`, `NEVER_EXPIRES`, `REGEX_BUDGET_MS` and `THINKING_OUTPUT_TOKENS`.
82
- - Options `maxToolCallsPerTurn` (`askGemini`) and `regexBudgetMs` (`tools`).
83
- - `DocumentMeta.jsonBytes`. Documents ingested before keep the planner's 8% rule.
84
-
85
- ## [0.4.0] - 2026-11-12
86
-
87
- Nothing to change in your code: the API, the tools and their results are those of 0.3.6 (compared
88
- call by call). Servers of 0.3.x and 0.4.0 can share a `FileDocumentStore` during a rolling update;
89
- 0.3.x servers ignore the new index files. The delete fix below holds once every server runs 0.4.0.
26
+ Each addition in one or two lines, with a link to the page that explains it. A short sample for
27
+ the ones most apps will use.
28
+
29
+ ### Changed: what works differently
30
+
31
+ One or two lines each.
90
32
 
91
33
  ### Fixed
92
34
 
93
- - **A document deleted on one server is no longer served by another.** Servers sharing a store
94
- kept a document in memory and answered from it until it expired, up to 72 hours after a delete.
95
- Every use of a kept document now asks the store first (`getMeta`, about a millisecond).
96
-
97
- ### Changed
98
-
99
- - **The memory cache is bounded in bytes** (`cacheBytes`, default 256 MB), not in documents. Six
100
- documents of 50 MB took over 600 MB before. `cacheSize` still caps the number when given. Calls
101
- that arrive together for a document that is not in memory open it once.
102
- - **Large documents are read by range on a store that can** (`FileDocumentStore`, or your own with
103
- `readTextRange`): a tool call reads the lines it needs, and a search reads the text 1 MB at a time,
104
- so memory no longer grows with file size and the number of users. Documents up to
105
- `wholeDocumentBytes` (2 MB) are loaded whole as before. Results are the same.
106
- - `FileDocumentStore` writes every file whole (to a temporary name, then renamed), and `sweep` no
107
- longer deletes a document whose metadata cannot be read unless that file is an hour old: on a
108
- shared volume it may be an upload in progress.
109
-
110
- ### Added
111
-
112
- - A line index per document (`<id>.idx` in `FileDocumentStore`, a few bytes a line), written at
113
- ingest. Documents from older versions get one the first time they are used.
114
- - `DocumentStore.readTextRange`, `putIndex` and `getIndex`: optional, for stores of your own.
115
- - `sweep` removes files that belong to no document, and temporary files, once they are an hour old
116
- (`orphanAgeMs`).
117
- - Options `wholeDocumentBytes`, `scanChunkBytes` and `maxConcurrentScans` (at most 4 searches of
118
- large documents at once per process; the others wait, and those of the same document share one
119
- pass over it). Decoded pieces of documents in use are kept within `cacheBytes`.
120
- - `get_document_overview` works out the number of parts of a file once per document, not on every call.
121
-
122
- ## [0.3.6] - 2026-11-11
35
+ Grouped by area. One or two lines each, written for an app developer, with the numbers that
36
+ matter.
37
+ -->
38
+
39
+ ## 0.7.0 — 2026-11-22
40
+
41
+ A question and an ingest now say what they do as typed events, in order: the plan, each model
42
+ request with its retries and usage, each tool call with how it ended, the answer's text, and the
43
+ result or the error at the end. `askStream` gives a question's events as an async iterable,
44
+ `writeSseEvents` sends them to a browser as Server-Sent Events, and an upload can answer with its
45
+ progress. The callbacks of 0.6.0 (`onText`, `onActivity`, `onStep`) get the same strings at the
46
+ same moments, and events carry no tool results, which hold document text, unless you ask
47
+ for them. A live check with the
48
+ Gemini API passed: the events of a search, of a question with an explorer and of a whole-file read
49
+ were counted and paired, and a question was sent end to end over SSE. See
50
+ [Events](docs/reference/events.md).
51
+
52
+ ### Upgrading: what you need to change
53
+
54
+ Code written for 0.6.0 compiles with 0.7.0 as it is. Every change to the public types is an
55
+ addition: new optional options and fields, an optional fourth parameter of
56
+ `ToolSet.executeWithFiles`, and new exports. `llm-large-files` adds `askStream`, `eventStream`,
57
+ `newRunId` and the types `AskEvent`, `IngestEvent`, `LibraryEvent`, `EventBase`, `EventError`,
58
+ `EventResult`, `EventStream`, `DocumentRef`, `IngestStage`, `NoticeCode`, `NoticeDisplay`,
59
+ `RequestRole`, `RequestPurpose`, `ToolOutcome`, `ExtractProgress`, `ToolCallHooks`,
60
+ `ToolRequestHandle`, `ToolRequestStart` and `ToolRequestEnd`; `llm-large-files/node` adds
61
+ `writeSseEvents`, `sseMessageOf` and the types `SseMessage` and `SseWriteOptions`;
62
+ `llm-large-files/gemini` adds the type `AskEvent`.
63
+
64
+ Some behavior is different. Check each point against your app:
65
+
66
+ - **Each entry of `AskResult.evidence` now has `callId`.** `askWithFiles` and `askGemini` set it
67
+ to the id of the tool call it came from (`"call_1"`, `"call_2"`…), the id its events use. Code
68
+ or a test that compares `result.evidence` with objects that have no `callId`, by deep equality
69
+ (`toEqual`, `assert.deepStrictEqual`), now fails.
70
+ **What to do:** add `callId` to the objects you compare with, or compare with `toMatchObject`.
71
+ `evidenceOf()` in a loop of your own does not set it.
72
+ - **A throw from `onActivity` during a whole-file read now ends the question.** In 0.6.0, a throw
73
+ of `onActivity` on the progress of `analyze_whole_document` ("Reading app.log: part 3 of 12…")
74
+ became the tool's error: the model was sent your error's message, and the question went on. Now
75
+ the read and the other calls of its turn stop, and `askWithFiles` throws that error. A throw of
76
+ `onEvent` there does the same.
77
+ **What to do:** nothing, unless your `onActivity` can throw, such as one that writes to a
78
+ connection that may have closed. Catch its errors inside it.
79
+ - **`ToolSet.executeWithFiles` takes an optional fourth argument, `hooks`** (`ToolCallHooks`). It
80
+ matters only for a `ToolSet` of your own, such as a wrapper around `files.tools()` in a
81
+ `LargeFiles` of your own. A wrapper that drops the argument still works, but `askWithFiles`
82
+ then gets no `tool.progress` events and no events for the requests of a whole-file read.
83
+ **What to do:** in such a wrapper, pass `hooks` on.
84
+ - **`ExtractInput` has an optional `onProgress`.** An extractor of your own works as before, and
85
+ its file reports no `extract` progress. An extractor that wraps a built-in one with an
86
+ `ExtractInput` of its own should pass `onProgress` on.
87
+ **What to do:** nothing; call it to report progress (see **New**).
88
+
89
+ ### New: what you can add
90
+
91
+ The samples assume what your app already has: `files` from `createLargeFiles()`, `model` from an
92
+ adapter, and the `documentIds` and `question` of the chat.
93
+
94
+ - **The events of a question: `AskOptions.onEvent`.** Every event of the question, in order:
95
+ `run.start`, `plan`, `request.start`, `retry`, `text`, `request.end`, `tool.start`,
96
+ `tool.progress`, `tool.end`, `notice`, and last `run.finish` or `run.error`. Each has `seq`
97
+ (1, 2, 3… without gaps), `runId` and `time`. Requests and tool calls come in pairs with ids
98
+ (`req_1`, `call_1`), and tool ends come in call order. Notices say what the callbacks said, and
99
+ three things they never did (`budget_reached`, `no_room`, `blocked`). Errors in events are told
100
+ in words for users: a model error by its kind and status, never in the provider's words, which
101
+ stay on the error that is thrown. See [`AskEvent`](docs/reference/events.md#askevent) and
102
+ [The order of the events](docs/reference/events.md#the-order-of-the-events).
103
+ - **`askStream(options)`**: `askWithFiles` as an async iterable of its events, with `result` and
104
+ `abort()`. Leaving the loop early stops the question; the loop never throws (read `run.error`,
105
+ or await `result`). The answer is asked for as it is written unless `streamText: false`. See
106
+ [`askStream`](docs/reference/events.md#askstreamoptions).
107
+
108
+ ```ts
109
+ import { askStream } from "llm-large-files";
110
+
111
+ const stream = askStream({ files, model, documentIds, messages: [{ role: "user", text: question }] });
112
+ for await (const event of stream) {
113
+ if (event.type === "tool.start") console.log(`${event.label}…`);
114
+ if (event.type === "text") process.stdout.write(event.delta);
115
+ if (event.type === "run.error") console.log(`Failed: ${event.error.message}`);
116
+ }
117
+ const result = await stream.result.catch(() => undefined); // keep result.toolTurns with the chat
118
+ ```
119
+
120
+ - **`eventStream(run, options?)`**: the same for any function that takes an `onEvent` and a
121
+ `signal`, such as `askGemini` or `files.ingest`. See
122
+ [`eventStream`](docs/reference/events.md#eventstreamrun-options).
123
+ - **`AskOptions.runId`**: the `runId` of the events, to tie them to a request of your app.
124
+ Defaults to `"run_"` and 16 hex digits; `newRunId(prefix?)` makes one.
125
+ - **`AskOptions.eventResults`**: put each tool result in its `tool.end` event, and `toolTurns` and
126
+ the full plan (each document's `DocumentMeta`) in the result of `run.finish` and `run.error`.
127
+ Off by default, since they hold document text: without it, that plan names the documents only. See
128
+ [Documents](docs/reference/events.md#documents-eventresults-and-eventresult).
129
+ - **`AskOptions.streamText`**: whether the model is asked for the answer as it is written. It
130
+ defaults to `true` with `onText` and in `askStream`, and to `false` otherwise, as 0.6.0 did:
131
+ `onEvent` alone never changes how the model is asked. See
132
+ [`streamText`](docs/reference/events.md#streamtext).
133
+ - **The events of an ingest: `IngestInput.onEvent` and `IngestInput.runId`.** `ingest.start`,
134
+ `ingest.progress` for each stage (`check`, `extract`, `pictures`, `decode`, `prepare`, `index`,
135
+ `store`, in pages, parts, bytes or characters, at most one every 12 ms for a stage, and the last
136
+ one), then `ingest.finish` with the `DocumentSummary`, or `ingest.error`. See
137
+ [`IngestEvent`](docs/reference/events.md#ingestevent).
138
+ - **`ExtractInput.onProgress`**, for an extractor of your own to report its progress, as the
139
+ built-in ones do for each page of a PDF and each part of a DOCX or PPTX. See
140
+ [`ExtractInput.onProgress`](docs/reference/events.md#extractinputonprogress-for-an-extractor-of-your-own).
141
+ - **`ToolCallHooks`**, the optional fourth argument of `ToolSet.executeWithFiles`: the progress
142
+ and the model requests of one call, for a loop of your own in which two whole-file reads run at
143
+ once. See [`ToolCallHooks`](docs/reference/events.md#toolcallhooks).
144
+ - **`writeSseEvents(response, events, options?)` and `sseMessageOf(event)`**, in
145
+ `llm-large-files/node`: events to a browser as Server-Sent Events, one message per event
146
+ (`id` is `seq`, `event` is `type`, `data` the event itself), with the event-stream headers,
147
+ keep-alive comments and back-pressure. It stops an `askStream` passed to it when the client goes
148
+ away. `sseMessageOf`, its default, sends the result of `run.finish` without `toolTurns`, `plan`,
149
+ `budget` and `lastUsage`. See
150
+ [`writeSseEvents`](docs/reference/events.md#writesseeventsresponse-events-options).
151
+
152
+ ```ts
153
+ import { askStream } from "llm-large-files";
154
+ import { writeSseEvents } from "llm-large-files/node";
155
+
156
+ // In your route, with Node's response.
157
+ const stream = askStream({ files, model, documentIds, messages: [{ role: "user", text: question }] });
158
+ await writeSseEvents(response, stream);
159
+ ```
160
+
161
+ - **Uploads with progress.** `createDocumentHandlers().upload` answers a request with
162
+ `Accept: text/event-stream` with `200` and the ingest's events, ending with `ingest.finish`
163
+ (its `document` is the summary a `201` holds) or `ingest.error` (its `error` is the message and
164
+ status a JSON answer would have). A missing name, a refused owner and a file too large still get
165
+ an HTTP error in JSON, and without the header nothing changes. See
166
+ [Uploads with progress](docs/reference/events.md#uploads-with-progress).
167
+ - **`askGemini` takes `onEvent`, `runId`, `eventResults` and `streamText`**, and passes them to
168
+ `askWithFiles`. See [`askGemini`](docs/reference/events.md#askgemini).
169
+
170
+ ### Changed: what works differently
171
+
172
+ Besides the points under **Upgrading**:
173
+
174
+ - **`Evidence.callId`**: each entry of `AskResult.evidence`, and of `partialResultOf(error)`,
175
+ names its tool call, as `tool.end` does.
176
+ - **A turn that fails stops its other tool calls.** When a turn ends with an error (the question
177
+ was stopped, or a callback threw), the calls of that turn still waiting for their turn do not
178
+ run, and those running are told to stop. In 0.6.0, after a callback threw, they went on
179
+ running after the question had thrown.
180
+ - **`examples/server.ts`** asks with `askStream` and sends the events with `writeSseEvents`. The
181
+ page shows the tool calls with how each ended, a counter for whole-file reads, the status line
182
+ and the answer, and uploads with progress. The tool rounds of each chat stay on the server, so
183
+ the page no longer sends them back, and the question's body has a size limit.
123
184
 
124
185
  ### Fixed
125
186
 
126
- - **A terminal escape without an end no longer deletes the rest of a file.** An `ESC ]` whose end
127
- (BEL, or `ESC \`) was not on its line removed everything up to the next escape, or to the end of
128
- the file: a log of 10,000 lines whose third line held a logged user agent `ua="evil␛]"` was
129
- stored as 3 lines, with no error. Now only those two characters go. The escapes that save and
130
- restore the cursor (`ESC 7`, `ESC 8`) and the like no longer leave a character behind.
131
- - **DOCX and PPTX files are read in one pass, a piece at a time.** The paragraph pattern scanned
132
- to the end of the file from every paragraph that was not closed: a DOCX of 900 bytes held the
133
- server for 8 seconds, and one of 10 KB would have held it for an hour. The new reader looks at
134
- each character once. It also:
135
- - refuses a file that unpacks to more than 100 times its size (past the first 16 MB) or to more
136
- than 128 MB of XML, as it unpacks, before that much is in memory. A DOCX of 160 KB that unpacked
137
- to 50 MB of XML was stored as 29 million characters; it is now refused at 16 MB, in 0.2 s;
138
- - reads a text box once, after the paragraph it is anchored in. Word writes each text box twice,
139
- and the paragraph it was anchored in lost its text after the box: a resume template lost its
140
- "Objective" heading;
141
- - no longer takes the tab stops of a paragraph for tabs, and reads PowerPoint's line breaks
142
- (`<a:br>` with its run properties inside), which were lost.
143
- - **Picture marks: forms painted inside forms cannot hold the server.** A form was read again each
144
- time it was painted, and the time limit was checked only between pages: a PDF of 3 KB whose
145
- forms each paint the next one 30 times ran the process out of memory. Now each form is decoded
146
- once per file, a page that paints more than 20,000 images or makes the reader go through more
147
- than 16 MB of content is marked as a drawing at once, and the time limit holds within a page.
148
- Such a file is now read in 0.6 s.
149
- - **`llm-large-files/node`: `get` and `remove` answer their errors.** A `getOwner` that threw, or a
150
- store call that failed, rejected the handler's promise, which ends a Node process that has no
151
- handler for it (Express 4, plain `node:http`). All three handlers now answer every error
152
- themselves:
153
- - an error with a `status` between 400 and 599, as `getOwner` can now throw to refuse a request,
154
- is answered with that status and its message;
155
- - a store that fails is a 500 that gives the error's code (`Upload failed (ENOSPC).`). It was a
156
- 422 with the error's message, which named the server's paths;
157
- - `getOwner` runs before the upload is read, so a refused upload is not buffered.
158
-
159
- ## [0.3.5] - 2026-11-11
160
-
161
- ### Added
162
-
163
- - **`explorerModel`: a second model for the searching and reading.** The application chooses the
164
- model, as before, in `geminiApi()` or `vertexAi()`. It can now name two. The explorer makes the
165
- tool calls (search, read, look at pages) and reads a whole file in parts; `model` then writes the
166
- answer from what the tools returned, in one request without tools. So the many requests of a
167
- search through a large file can go to a cheaper or faster model.
168
- `geminiApi({ apiKey, model, explorerModel: process.env.GEMINI_EXPLORER_MODEL })`: left out,
169
- empty, or the same as `model`, one model does both, and the requests are those of 0.3.0 (checked
170
- byte for byte over seven scenarios). See
171
- [An explorer model](docs/configuration.md#an-explorer-model).
172
- - An endpoint of your own takes the explorer's URL as `explorerUrl`. It is called with the same
173
- headers.
174
- - `explorerGenerationConfig` is the explorer's `generationConfig`, for two models that do not
175
- take the same settings. It defaults to `generationConfig`. `analysisConfig` applies to the part
176
- reads of a whole-file read, which are the explorer's when there is one.
177
- - The answering model gets the explorer's tool calls and their results, pages included. It does
178
- not get the explorer's thoughts, thought signatures or words, and `text` and `onText` carry
179
- only the answer. The answer is always a request of its own, so a question takes one request
180
- more than with one model.
181
- - Checked live with Flash-Lite models, on the Gemini API and on Vertex AI, between Gemini 3.1 and
182
- 3.5 and between Gemini 2.5 and 3.5, in both directions, with thinking on and off: counts and
183
- causes from a searched log, a whole-file read, and a chart and a photo from pages that the
184
- explorer looked at. Every answer was right. `gemini-3.5-flash-lite` as explorer stopped with
185
- `DONE` each time, at one output token.
186
- - `EXPLORER_INSTRUCTION` and `FINAL_ANSWER_WITHOUT_TOOLS`: the two texts that `askGemini` adds for
187
- an explorer.
188
-
189
- ## [0.3.0] - 2026-11-10
190
-
191
- The model can look at the pages of a large PDF. Until now such a PDF reached it as text only, and
192
- pictures, charts and diagrams were lost. Everything here is off until you turn it on: an
193
- application that changes nothing, and does not install the new optional dependency, sends the same
194
- requests as with 0.2.0 (checked byte for byte against the published 0.2.0 over eight scenarios).
195
-
196
- ### Added
197
-
198
- - **`view_pages`: the real pages of a PDF, on request.** The tool cuts up to five pages out of the
199
- uploaded file and returns them as one small PDF, which Gemini reads like any PDF. Asked which bar
200
- of a chart is tallest, `gemini-3.5-flash-lite` said from the text alone that it could not see the
201
- chart; with the tool it looked at the page unasked and answered correctly. For ten questions that
202
- the text answers, it did not look at a page once. A page costs about 530 tokens. See
203
- [Pictures in PDFs](docs/configuration.md#pictures-in-pdfs) for the limits and the measurements.
204
- - It needs the new optional dependency `@cantoo/pdf-lib`, and the uploaded file (next item).
205
- - `askGemini` offers it for every PDF whose original is kept, also for one whose text fits in
206
- the prompt (a slide deck of photos has little text). `viewPages: false` turns it off.
207
- It works on the Gemini API and on Vertex AI. `toolFilePlacement: "beside"` sends the pages in
208
- a user turn of their own instead of inside the function response: Gemini 2.5 needs that, as it
209
- does not see a file inside a function response.
210
- - In a loop of your own: `prepare(ids, base, { viewPages: true })` lists the PDFs in
211
- `PreparedContext.viewable`, `tools(documents, { viewPages })` declares the tool, and
212
- `ToolSet.executeWithFiles(name, args, { maxFileBytes, maxPages })` returns `{ result, files }`.
213
- The tool is declared only on request, and `execute()` answers it with an error, because a loop
214
- that drops the file would tell the model that pages are attached with nothing attached.
215
- - Search and read results carry page numbers (`page`, `pages`) for a PDF that can be shown.
216
- - **`keepOriginals`: keep the uploaded file.** `createLargeFiles({ keepOriginals: ["pdf"] })`
217
- stores the file next to its text. It is off by default, because a kept file takes disk space, up
218
- to the upload limit, until the document expires. `DocumentStore` has two new optional methods,
219
- `putOriginal` and `getOriginal`; a store without them works as before and keeps nothing.
220
- `FileDocumentStore` writes `<id>.bin`, and delete, expiry and sweep remove it.
221
- `DocumentMeta.originalKept` records it, and `files.getOriginal(id, { owner })` returns the file
222
- to its owner.
223
- - **Scanned PDFs of up to 30 pages are accepted** when their original is kept: the model reads them
224
- by looking at the pages. `scannedPdfPages` sets the limit, and 0 refuses them as before. A longer
225
- scan, and any scan without a kept original, is still refused.
226
- - `geminiFunctionResponseTurns(answers, { files })`: the turns that answer a model turn's function
227
- calls, for a loop of your own. `geminiFunctionResponses` takes the files of each call and puts
228
- them inside its function response.
229
- - `createPdfExtractor({ pictures })`, `ExtractInput.scannedPages`, `MAX_VIEW_PAGES`,
230
- `FINAL_ANSWER_AFTER_PAGES`, and the types `ToolFile`, `ToolOutput`, `ToolFileLimits`,
231
- `PrepareOptions`, `GeminiToolAnswer` and `GeminiToolFilePlacement`.
232
-
233
- ### Changed
234
-
235
- - **A page of a PDF that shows a picture is marked**, with one line under its header:
236
- `[Picture on this page. This text cannot show it.]`. A picture is images that cover 3% of the
237
- page or more, other than a logo or background that is on most pages; a drawing is shapes filled
238
- in three or more colours, outside the tables. The pages are found from the structure of the file,
239
- without decoding any image: a PDF of 200 photos took 0.3 s to ingest before and takes 0.8 s now.
240
- This needs `@cantoo/pdf-lib`. Without it, and with `createPdfExtractor({ pictures: false })`, the
241
- text is exactly that of 0.2.0. Documents already in a store keep the text they were ingested
242
- with.
243
- - `ToolSet` has a new method, `executeWithFiles`, `LargeFiles` has `getOriginal`, and
244
- `PreparedContext` has `viewable`. Code that builds these objects itself (a test double, for
245
- example) has to add them.
246
-
247
- ### Known limits
248
-
249
- - A chart in one or two colours, and a drawing made only of lines, is not marked. The model can
250
- still look at the page: it did so for a one-colour chart that had only a caption.
251
- - Every look reads the whole PDF into memory: 0.06 s for 100 MB of photos, but 4 to 5 seconds and
252
- 700 MB for a file of 330,000 objects. A file that declares more objects than memory allows is
253
- refused. Reading cannot be interrupted, so a crafted PDF can hold the process for a long time:
254
- see [Security](docs/security.md#reading-pdfs-for-pages-and-pictures).
255
- - Tested with PDFs made by Chrome, Word and PowerPoint. PDFs made by LaTeX and InDesign were not
256
- tested. For FPDF, Ghostscript and scanners, the structures they are known to write were tested
257
- with files made for the purpose, not with files from those tools. Encrypted PDFs were tested
258
- with files encrypted by the library itself, and confirmed as encrypted by pdf.js.
259
-
260
- ## [0.2.0] - 2026-11-10
187
+ - **The status line of the example page shows.** The page of `examples/server.ts` wrote its
188
+ status to `status`, which in a browser is `window.status`, not the element with that id: retries,
189
+ "Writing the answer…", errors and the usage at the end never showed. The page now looks the
190
+ element up by its id.
191
+
192
+ ## 0.6.0 — 2026-11-22
193
+
194
+ Questions fail less often, and when one fails, you can tell why and keep what it found: every
195
+ model error has a kind, a request too large for the model is made smaller and sent again, a model
196
+ that goes silent is stopped after a wait, an empty or broken turn is asked for again, and a call
197
+ whose result is still in the conversation is answered with a pointer, not run again. Uploads
198
+ are guarded: an upload with an empty owner is refused, `files.tools()` checks the owner of each
199
+ document, many files built to exhaust the server are refused, and ingest lets other requests run
200
+ while it reads a file, within limits on its text, its pages and its time; one page of a PDF can
201
+ still hold the server, and a crafted PDF can still run it out of memory. A search shows the last
202
+ matching line, a text file in an older encoding, such as a Hebrew CSV from Excel, is read in that
203
+ encoding, and the rest are fixes in the tool loop, whole-file reads, the three adapters and the
204
+ text the model is sent. Some of these change what the library sends, throws or refuses: read
205
+ **Upgrading** before you update.
206
+
207
+ ### Upgrading: what you need to change
208
+
209
+ Code written for 0.5.0 compiles with 0.6.0 as it is, but for two cases. The turns of
210
+ `geminiFunctionResponses` and `geminiFunctionResponseTurns` now have `GeminiPart[]` parts, where
211
+ they had `unknown[]` (see **Changed**). Code that adds to those `parts` a string, or a value typed
212
+ `unknown`, `object` or by an interface (another SDK's `Part`), no longer compiles: add an object
213
+ literal, or `{ ...part }`. And an object typed as `ModelRequestError` or one of its subclasses,
214
+ but made other than by its constructor, needs the new `kind`. Every other change to the public
215
+ types is an addition: new fields and new optional options (under **New**), wider parameter types
216
+ (`parseSseJson` takes hooks and Node streams), and new exports. `llm-large-files` adds
217
+ `partialResultOf`, `classifyModelError`, `errorKindOf`, the error class `SseEventTooLongError`, the
218
+ constants `DEFAULT_FIRST_BYTE_TIMEOUT_MS`, `DEFAULT_IDLE_TIMEOUT_MS`, `DEFAULT_MAX_TEXT_BYTES`,
219
+ `DEFAULT_MAX_PDF_PAGES` and `DEFAULT_INGEST_TIMEOUT_MS`, and the types `ModelErrorKind`,
220
+ `ModelErrorClass`, `IdleWaits`, `RetryNotice` and `SseHooks`; `llm-large-files/gemini` adds
221
+ `partialResultOf` and `SseEventTooLongError`. One member is marked deprecated:
222
+ `ModelAdapter.estimateTokens` (see "Your own adapter" below).
223
+
224
+ Some behavior is different. Check each point against your app.
225
+
226
+ Uploads and stored documents:
227
+
228
+ - **An upload whose owner is empty is refused.** An owner of `""` (what `user?.id ?? ""` gives a
229
+ caller who is not signed in), of spaces only, or `null` was one owner shared by every such
230
+ caller: each of them could read and delete the documents of the others whose IDs it had.
231
+ `files.ingest` now throws a `TypeError`:
232
+ `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.`
233
+ So does an owner from JavaScript that is neither a string nor a finite number (`req.user` in
234
+ place of `req.user.id`, `true`, `NaN`, an array). `createDocumentHandlers` answers such an
235
+ upload with a 500 before it reads the body, and logs nothing:
236
+ `{ "error": "Upload failed (empty owner)." }` when `getOwner` returns `""`, spaces only or `null`
237
+ (a user header that arrives empty gives `""`), and
238
+ `{ "error": "Upload failed (owner is not a string)." }` for the others. 0.5.0 accepted all of
239
+ these owners. Signed-in uploads and numeric owners are unchanged. Reads and deletes with
240
+ `owner: ""` work as before, so the documents stored with that owner stay readable until they
241
+ expire.
242
+ **What to do:** in `getOwner`, return the user's ID, not the user object. Where every upload
243
+ needs a signed-in user, throw an error with `status: 401` for a request without one
244
+ ([Requiring a signed-in user in the handlers](docs/security.md#requiring-a-signed-in-user-in-the-handlers)).
245
+ Only where anonymous uploads are meant, return `undefined` for such a caller
246
+ (`user?.id || undefined`): anyone with the ID of such a document can then read and delete it, as
247
+ the message says. See [Ownership](docs/security.md#ownership) and
248
+ [`DocumentHandlerOptions`](docs/reference/node.md#documenthandleroptions).
249
+ - **Uploads past the new limits are refused.** `files.ingest` throws, and
250
+ `createDocumentHandlers` answers 422 with the message:
251
+ - a PDF of more than `maxPdfPages` pages (5,000 by default), before any page is read:
252
+ `This PDF has 6,200 pages, more than the 5,000 read from one file. Split it, and attach the part you need.`
253
+ - a file whose text takes more than `maxTextBytes` in UTF-8 (100 MB by default, or
254
+ `maxUploadBytes` when you set that higher):
255
+ `This PDF holds more than 100 MB of text, more than is kept from one file. Split it, and attach the part you need.`,
256
+ or for a text file `notes.txt holds more than 100 MB of text, …` with the same end. A file's
257
+ text can be larger than the file: the text of a DOCX is often 2 to 4 times its size, a UTF-16
258
+ file of Chinese or Japanese text grows by half in UTF-8, and a small PDF can draw far more
259
+ text than its size.
260
+ - a DOCX or PPTX of more than 32 million characters of text (about 10,000 dense pages), whatever
261
+ `maxTextBytes` allows:
262
+ `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.`
263
+ - a PDF that draws more than 100 times its size in text, past the first 16 MB:
264
+ `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.`
265
+ Real PDFs hold less text than their size.
266
+ - files built to exhaust the server, which no program writes: a PDF whose page tree lists one
267
+ page more than once; a DOCX or PPTX with paragraphs nested more than 32 deep, more than
268
+ 1,000,000 paragraphs with text, more than 20,000 parts
269
+ (`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.`),
270
+ or a list of parts that would take JSZip far more memory or time than an Office document needs
271
+ (the list is read before JSZip reads it, the way JSZip will, not from the count the file gives);
272
+ - with `@cantoo/pdf-lib` installed, a PDF with a page whose content would take pdf.js far longer
273
+ to read than its file explains (past about 1 to 1.5 s of pdf.js, or 32 times the size of the
274
+ file when that is more), found before pdf.js reads any page
275
+ ([Pages that would hold the server](docs/guides/pdfs.md#pages-that-would-hold-the-server)):
276
+ `Page 1 of this PDF draws far more than its file holds, and reading it would hold the server for a long time. A file built that way is not read: it may be built to exhaust the server. Print it to a new PDF, and attach that.`
277
+ Pages that each pass but add up to more than four times as much are refused with
278
+ `This PDF draws far more than its file holds, …` with the same end. A page whose content is
279
+ stored in a way that cannot be decoded before pdf.js reads it (a filter that only images use,
280
+ such as JPEG) is refused with
281
+ `Page 1 of this PDF stores its content in a way that cannot be checked before it is read, so it is not read. Print it to a new PDF, and attach that.`
282
+ The pages of the documents tested ran up to 11% of that limit.
283
+
284
+ **What to do:** nothing, unless your users upload PDFs of more than 5,000 pages, or files with
285
+ more than 100 MB of text: then raise `maxPdfPages` or `maxTextBytes`. If real PDFs of your users
286
+ are refused for a page that would hold the server, read them with
287
+ `createPdfExtractor({ checkPages: false })`, in a process of its own. Every message is in
288
+ [PDFs and other formats](docs/guides/pdfs.md#what-is-refused).
289
+ - **An ingest that takes more than 2 minutes throws.** `ingestTimeoutMs` (120,000 by default)
290
+ bounds the extraction, the line index and the log profile, not the store's writes. Past it,
291
+ `ingest` throws
292
+ `report.pdf took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.`,
293
+ stores nothing, and `createDocumentHandlers` answers 422 with that message. An extractor of your
294
+ own that calls a slow service, such as OCR of a long scan, can take longer than that.
295
+ **What to do:** for such an extractor, raise `ingestTimeoutMs`, or set it to 0 for no limit, and
296
+ pass `input.signal` on to the work it does (`fetch(url, { signal: input.signal })`): at the limit
297
+ `ingest` stops waiting for the extractor, but only the extractor can stop its own work. If you
298
+ ingest in a worker or a process with a timer of its own, set that timer above
299
+ `ingestTimeoutMs`, so that the user gets the library's message.
300
+ - **With `@cantoo/pdf-lib` installed, every PDF is read with it before its text.** The PDF
301
+ extractor reads the file into objects before pdf.js reads any page, for the page check and the
302
+ picture marks together; 0.5.0 read it after the text, for the marks only. With picture marks on
303
+ (the default), that costs nothing measurable: PDFs of 300 to 2,000 pages took the same time
304
+ within the spread of three runs, and the longest stall did not grow. With `pictures: false`,
305
+ 0.5.0 did not read the file this way at all, and now does, for the page check: 0.1 to 0.3 s more
306
+ for 300 to 2,000 pages, up to 90 MB more memory at the peak, and, for the first PDF of a process,
307
+ about 0.4 s in one block to load `@cantoo/pdf-lib`, unless the server loads it when it starts
308
+ ([Deployment](docs/guides/deployment.md#uploads-and-ingest)). See
309
+ [Measurements](docs/measurements.md#the-server).
310
+ **What to do:** nothing, unless you set `pictures: false` to keep ingest light, in a process with
311
+ little memory to spare. Then give it that room, or pass
312
+ `createPdfExtractor({ pictures: false, checkPages: false })` to read PDFs as 0.5.0 did, without
313
+ the page check.
314
+ - **`files.tools()` answers a document whose owner does not match as no longer available.** Each
315
+ tool call now compares the owner stored with the document with the `owner` of the `DocumentMeta`
316
+ that `tools()` was handed. When they differ, the call answers the model
317
+ `doc_… is no longer available on the server. Ask the user to attach the file again.`, and
318
+ `view_pages` shows no page. A document stored without an owner is open to any metadata, as
319
+ before. The metadata that `prepare(ids, base, { owner })` and `getMeta(id, { owner })` return
320
+ carries the stored owner, so `askWithFiles`, `askGemini`, and a loop of your own written as the
321
+ docs show, work as before.
322
+ **What to do:** nothing, unless your loop builds `DocumentMeta` objects itself, from IDs or from
323
+ your own database (a `DocumentSummary` has no owner). Take them from `prepare` or `getMeta` with
324
+ the caller's owner. See [Security](docs/security.md#tool-scoping).
325
+ - **A text file that is not UTF-8 is read in the encoding it was saved in.** 0.5.0 decoded every
326
+ text, log, CSV, JSON and Markdown file as UTF-8: a CSV that Excel saved in windows-1255 was
327
+ stored as replacement characters (U+FFFD), and accepted without a word. `files.ingest` now reads
328
+ a file in one of these encodings when the letters of its lines show which, and records it in
329
+ `meta.encoding`: `windows-1255` (Hebrew; ISO-8859-8 too), `windows-1256` (Arabic),
330
+ `windows-1251` (Cyrillic), `shift_jis` (Japanese in Shift_JIS, half-width katakana too) and
331
+ `windows-1252` (Western European; ISO-8859-1 too). The encoding is chosen on the lines that are
332
+ not UTF-8 and hold letters, wherever they are in the file, up to 64 KB of them. A line that is
333
+ valid UTF-8 is read as UTF-8 all the same. A byte that the encoding does not have is stored as
334
+ U+FFFD, and counted in `meta.replacedCharacters`.
335
+
336
+ No text file is refused for its encoding. Valid UTF-8 and UTF-16 files are decoded as before. A
337
+ file is read as UTF-8, as 0.5.0 read it, with its characters that are not valid counted in
338
+ `meta.replacedCharacters`, when its encoding is not recognized, when at least as many of its
339
+ lines count as UTF-8 as count as not, or when at most one line in 200 is not UTF-8 (a log cut at
340
+ a byte count, a log with stray bytes): those lines become U+FFFD even when they are in an older
341
+ encoding. As a rule, these are not recognized: Greek, Turkish, Central European (windows-1250),
342
+ Icelandic, KOI8-R, the DOS code pages (437, 850, 866), Chinese, Korean and Thai, and Japanese
343
+ with few or no kana. Some files are read in a wrong encoding, which `meta.encoding` names:
344
+ Hungarian in windows-1250 or ISO-8859-2 as windows-1252, with õ and û in place of ő and ű (a
345
+ search for a word with ő or ű finds nothing); ISO-8859-15 without œ as windows-1252, with ¤ in
346
+ place of € (with œ in its words, it is most often read as UTF-8 with U+FFFD); and a short file,
347
+ or one long line, whose few stray bytes happen to fit another encoding
348
+ ("Straße" saved in DOS code page 850 as windows-1252 "Straáe"). An editor that opens such a file
349
+ as UTF-8 shows the lines read in an older encoding as �: a person who checks the file there does
350
+ not see what the model reads.
351
+
352
+ A `DocumentStore` of your own must keep the two new fields, as it keeps the rest of `meta`
353
+ ([Writing a store of your own](docs/guides/storage.md#writing-a-store-of-your-own)). One that
354
+ checks `meta` against a fixed list of fields (a MongoDB `$jsonSchema` with
355
+ `additionalProperties: false`) refuses the ingest of every text file that is not valid UTF-8,
356
+ and `createDocumentHandlers` then answers 500 `{ "error": "Upload failed." }`. One that drops
357
+ them (fixed columns of a table, a Mongoose schema in strict mode) keeps the text, read right, but
358
+ the model is not told how it was read. The upload answer (`DocumentSummary`) holds both
359
+ fields when they are set.
360
+ **What to do:** nothing, if your store keeps `meta` whole and your client accepts fields it
361
+ does not know. Show `meta.encoding` to the user ("read as windows-1255"), and when letters look
362
+ wrong, ask for the file in UTF-8 (in Excel, "CSV UTF-8 (Comma delimited)"). Documents stored
363
+ before the upgrade from files in these encodings still hold U+FFFD: ingest them again. See
364
+ [Text encodings](docs/guides/pdfs.md#text-encodings), how the encoding is chosen in
365
+ [How it works](docs/how-it-works.md#text-encodings),
366
+ [Text files that were not UTF-8](docs/security.md#text-files-that-were-not-utf-8) and
367
+ [`DocumentMeta`](docs/reference/library.md#documentmeta).
368
+ - **Some files are stored with other text than 0.5.0 stored.** Besides a text file that is not
369
+ valid UTF-8 (above), ingest now removes characters that show nothing, such as tag characters,
370
+ zero-width spaces and control characters U+0080-U+009F, and the terminal escape sequences that
371
+ start with U+009B; makes U+0085 a line break in a text that has no other; marks text that Word
372
+ hides, line by line; and marks the heading of a slide that the slide show skips (see
373
+ **Changed**). File names lose tag characters, zero-width spaces and the other characters that
374
+ show nothing too. Their control characters, line and paragraph separators and text-direction
375
+ controls, the marks of right-to-left text included, became a space in 0.5.0 already, and still
376
+ do: an escape sequence loses only its ESC (`re\x1b[31mport.txt` is stored as `re [31mport.txt`).
377
+ Lines move in three cases: in a DOCX with hidden text, in a text whose records end with U+0085,
378
+ and after a line of more than 2,000 characters that lost such characters, which can now be cut
379
+ into fewer lines. A file with none of these gets the same text and line index as 0.5.0 gave it,
380
+ and the same outline, but in a document of more than 400 headings with 20 to 399 at the top
381
+ level (see **Fixed**, Ingest). Documents stored before the upgrade keep their text and outline
382
+ until they expire.
383
+ **What to do:** nothing. To have a document stored before the upgrade read the new way, ingest
384
+ its file again.
385
+ - **An `unpdf` that cannot read PDFs on your version of Node is refused, with what to install,
386
+ and unpdf 2 is accepted.** With 0.5.0, on Node 20.19 and 22.12, unpdf 1.5.0 to 1.6.0 stopped the
387
+ whole process at the first PDF (`TypeError: Promise.try is not a function`, thrown where nothing
388
+ could catch it). On Node 20, unpdf 1.9 and later failed every PDF with
389
+ `Serverless PDF.js bundle could not be resolved: ReferenceError: Iterator is not defined`. Now
390
+ `files.ingest` throws, and `createDocumentHandlers` answers 422, with a message that names the
391
+ major version of Node and says what to install:
392
+ - unpdf 1.5.0 to 1.6.0 on Node 22:
393
+ `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.`
394
+ On Node 20 the message ends `Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 24 or later.`
395
+ - unpdf 1.9 and later, 2.x included, on Node 20:
396
+ `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.`
397
+ The part in parentheses is unpdf's own message.
398
+
399
+ The optional peer range of `unpdf` is now `^1.4.0 || ^2.0.0`; it was `^1.4.0`. An app that
400
+ upgrades keeps the unpdf its lock file has. On Node 24 and later, a new `npm install unpdf` next
401
+ to 0.6.0 installs unpdf 2 and saves `^2` in `package.json`, where it got 1.9.1 next to 0.5.0. On
402
+ Node 20 and 22, npm 11 (the version checked) picks a 1.x whose engines fit: 1.7.0 and 1.9.1.
403
+ **What to do:** nothing, if your PDFs are read today. Otherwise install the unpdf that runs on
404
+ your Node: on Node 20, 1.4.0 or 1.6.1 to 1.8.1 (1.7.0 is the last that does not ask for
405
+ Node 22); on Node 22, 1.4.0, or 1.6.1 or a later 1.x; on Node 24 and later, any version from
406
+ 1.4.0, 2.x included. To go back to 0.5.0 after moving to unpdf 2, install both in one command:
407
+ `npm install llm-large-files@0.5.0 unpdf@^1`. `npm install llm-large-files@0.5.0` alone stops
408
+ with `ERESOLVE` and changes nothing. Restoring `package.json` and `package-lock.json` together
409
+ works too. See [PDFs and other formats](docs/guides/pdfs.md#formats).
410
+ - **One page of a PDF still holds the server while it is read, and a crafted PDF can still run it
411
+ out of memory.** 0.5.0 did the same. Between two pages, the PDF extractor lets other requests run
412
+ and looks at the time limit and the signal; within a page it cannot, and neither
413
+ `ingestTimeoutMs` nor `IngestInput.signal` cuts a page short. The page check (above) refuses the
414
+ pages that would take far longer than their file explains. What it leaves:
415
+ - a page that passes holds the server for up to about 1.5 s in a small file, and longer in a
416
+ large one: a page of a 10 MB file may run 320 MB of content, about a minute of pdf.js;
417
+ - without `@cantoo/pdf-lib`, on a file it cannot read or that declares more than 150,000
418
+ objects, and with `checkPages: false`, no page is checked: a 3 KB page of forms inside forms
419
+ held the event loop for 13 s, and one of 4 KB for about 100 s. A file built to be read one way
420
+ by `@cantoo/pdf-lib` and another way by pdf.js passes the check too;
421
+ - `@cantoo/pdf-lib` reads each object in one step, at ingest and on each look of `view_pages`:
422
+ about 0.1 to 0.35 s for each MB of one object (a crafted PDF of 16 MB with one array of numbers
423
+ held the server 1.6 to 3.2 s at ingest, and 1.7 to 3.5 s on each look), and 0.7 s for each
424
+ million objects that a cross-reference stream declares;
425
+ - a DOCX or PPTX packed hundreds of times tighter than documents are holds it for about 0.2 s at
426
+ a time while JSZip unpacks a piece.
427
+
428
+ Nothing checks the memory an object of a PDF takes before pdf.js or `@cantoo/pdf-lib` builds it,
429
+ and a stream unpacked twice packs objects thousands of times. Measured on Node 24: a PDF of 732
430
+ bytes whose object stream holds 4 MB of empty dictionaries ran a heap of 512 MB out of memory at
431
+ ingest; one array of one-digit numbers in a PDF of 16 MB ran a heap of 256 MB out of memory at
432
+ ingest, and one of 512 MB on a look at its pages; a PDF of 1.6 KB whose object stream unpacks to
433
+ 512 MB was read with 20 MB of heap, but the process took 1.6 GB, outside the heap, where
434
+ `--max-old-space-size` does not limit it; and `@cantoo/pdf-lib` keeps every name and reference it
435
+ reads for the life of the process, so that files of 9 KB that each declared a million new objects
436
+ ran a heap of 512 MB out of memory at the fourth ingest. A check of each object before it is
437
+ built is not in 0.6.0: it would be easy to get around. See
438
+ [Objects of a PDF](docs/security.md#uploads) and the [measurements](docs/measurements.md#the-server).
439
+ **What to do:** if your users can upload files you do not trust, ingest them in a child process
440
+ of their own, with its own `--max-old-space-size` and a memory limit of its own, such as a
441
+ container of its own, as [Deployment](docs/guides/deployment.md#uploads-and-ingest) shows: such
442
+ a file then holds or stops that process, not your server, and its time limit stops it. Not in a
443
+ worker thread, as the security page of 0.5.0 suggested: a `--max-old-space-size` of the process,
444
+ on the command line or in `NODE_OPTIONS`, replaces the `resourceLimits.maxOldGenerationSizeMb`
445
+ of every worker (with `--max-old-space-size=1024`, a worker given 512 MB had 1,216 MB on
446
+ Node 24), and a worker that runs out of memory can stop the whole process. If you ingest in a
447
+ worker, move to the child process of `ingestInProcess` in that guide. Do not offer `view_pages`
448
+ on their documents (`viewPages: false`), or keep no PDF originals: a look parses the file again
449
+ on the server that answers the question, can need more memory than the ingest did, and what
450
+ `@cantoo/pdf-lib` keeps there comes back only when that server restarts
451
+ ([Memory on each server](docs/guides/deployment.md#memory-on-each-server)).
452
+ - **An upload whose store fails while it writes is answered 500, not 422.** When `put`,
453
+ `putOriginal` or `putIndex` throws an error that has no `status` or `statusCode` from 400 to 599
454
+ and is not a Node system error, `createDocumentHandlers` answers 500
455
+ `{ "error": "Upload failed." }`. 0.5.0 answered 422 with the error's own message, which may name
456
+ a database host. A thrown value that is not an `Error` also gets 500 "Upload failed.", where it
457
+ was 422 with the value as text. Errors with a status, Node system errors (an `Error` or not) and
458
+ files that cannot be read are answered as before.
459
+ **What to do:** for a more specific answer, throw your store's write errors with a `status` and
460
+ a message of your own (a 503 that says to try again), and log the cause in your store: the
461
+ handlers log nothing. Two paths still answer a store's error 422 with its message: an `ingest` of
462
+ your own that throws a new error in its place, as `ingestInProcess` in
463
+ [Deployment](docs/guides/deployment.md#uploads-and-ingest) does, and a route of your own, as in
464
+ [Web app](docs/guides/web-app.md#filesingest-and-its-errors). A status on the error avoids it.
465
+ See the [node reference](docs/reference/node.md#uploadrequest-response).
466
+
467
+ Model errors and retries:
468
+
469
+ - **A model that sends nothing now fails, after a wait.** In 0.5.0 a chat request had no time
470
+ limit: a provider that stopped answering held the question, and the user, until your own
471
+ timeout. Now each adapter aborts a chat request that gets nothing for 600 s before the first
472
+ piece of its reply, or for 300 s between two pieces, and sends it once more; `onActivity` then
473
+ says "The model sent nothing for too long. Trying again…". If that try is silent too, the
474
+ question throws a `ModelRequestError` with `kind: "timeout"` and `status: 0` ("Gemini sent
475
+ nothing for 600 s."). A reply whose text was already streamed to the user is not sent again: it
476
+ fails at once. Headers do not count as a piece, because a model that thinks sends nothing until
477
+ it has thought; keep-alives count. A reply that keeps arriving has no limit. A reply that is not
478
+ streamed comes whole at the end, so it must be written within `firstByteTimeoutMs`: Gemini and
479
+ OpenAI-compatible requests without `onText` (an explorer's requests among them), Gemini
480
+ requests to an endpoint without `streamUrl`, and every request of `openAiCompatible()` or
481
+ `anthropic()` with `stream: false`. Part reads of a whole-file read are not watched this way:
482
+ they keep their limit of 180 s.
483
+ **What to do:** handle the `"timeout"` kind (see the sample under **New**). With the defaults,
484
+ a model that never answers fails after about 20 minutes (two waits of 600 s). To give up
485
+ sooner, or never, set `firstByteTimeoutMs` and `idleTimeoutMs` on `askGemini`, `gemini()`,
486
+ `openAiCompatible()` or `anthropic()`; `0` waits without end, as 0.5.0 did. A proxy, load
487
+ balancer or gateway that closes a silent connection sooner still closes it first: keep the
488
+ timeouts on the way longer than these waits, or set the waits shorter. See
489
+ [Waits on a silent model](docs/guides/errors-and-reliability.md#waits-on-a-silent-model) and
490
+ [The order of the timeouts](docs/guides/deployment.md#the-order-of-the-timeouts).
491
+ - **A reply cut off on its way is sent again, and can fail a question after its text was shown.**
492
+ A stream that closes without saying why it ended, and DeepSeek's `insufficient_system_resource`,
493
+ are no longer taken for a whole reply (see **Fixed**), and a reply of HTTP 200 whose body is
494
+ empty is no longer a `SyntaxError` (below). Such a reply is sent again when none of it was
495
+ shown (see **Changed**, The adapters). When some of it was already streamed to the user, the
496
+ question throws at once: a `ModelRequestError` with status 0 and kind `"unreachable"`
497
+ ("Gemini's reply ended before it was complete."), or status 503 and kind `"server"` for
498
+ DeepSeek. In 0.5.0 the cut text was returned as the answer.
499
+ **What to do:** if you stream with `onText`, handle an error that comes after part of the
500
+ answer was shown: mark that text as incomplete and offer to ask again. `partialResultOf(error)`
501
+ has what the question found.
502
+ - **Quota errors are not sent again.** These now have `kind: "quota"`, and are thrown at once:
503
+ OpenAI's `insufficient_quota`, inside a stream too (HTTP 429 there); a Gemini quota per day
504
+ (HTTP 429 whose `details` name a quota per day, or, on Vertex AI, only its message); HTTP 402
505
+ (DeepSeek's "Insufficient Balance", OpenRouter's "Insufficient credits"); Claude's "Your credit
506
+ balance is too low" (HTTP 400); and Claude's spending limits ("You have reached your API usage
507
+ limits"), which come as HTTP 429 with `enforced_spend_limit_reached`, or as HTTP 400. 0.5.0 sent
508
+ the ones of HTTP 429 again three times (the default of `retry.retries`). A Gemini quota per
509
+ minute is `"rate_limit"`, and is waited for as before.
510
+ **What to do:** if you show "busy, try again" for every HTTP 429, show another message for
511
+ `"quota"`, and tell whoever runs the service: trying again soon does not help.
512
+ - **A request larger than the tokens a minute allows is made smaller, not sent again as it was.**
513
+ This covers OpenAI's "Request too large for gpt-4o … on tokens per min (TPM): Limit 30000,
514
+ Requested 45237" (HTTP 429) and Groq's "… on tokens per minute (TPM): Limit 6000, Requested 6438"
515
+ (HTTP 413 or 429), and the same per day: kind `"context_overflow"`, with `limitTokens` and
516
+ `requestedTokens`. 0.5.0 sent the 429 again three times as it was, though only a smaller request
517
+ can pass. Now the loop shortens older tool results, or plans the files again for that limit, as
518
+ for a request too large for the model (see **Changed**), and a part read is read in halves. The
519
+ steps say so: "The first request was larger than the 30,000 tokens a minute that the provider
520
+ allows: the files were planned again to fit it", or "The request was larger than the provider
521
+ allows in a minute: older tool results were shortened, and it was sent again". `withRetry` does
522
+ not send an error of kind `"context_overflow"` again, whatever its status.
523
+ **What to do:** nothing, unless an adapter of your own sets `kind: "context_overflow"` on an
524
+ error that a wait would mend. See
525
+ [A request too large for the model](docs/guides/errors-and-reliability.md#a-request-too-large-for-the-model).
526
+ - **A reply of HTTP 200 whose body is not JSON is a `ModelRequestError`, not a `SyntaxError`.** A
527
+ page from a proxy or a gateway that answered in the model's place (a sign-in page) now throws a
528
+ `GeminiRequestError`, `OpenAiRequestError` or `AnthropicRequestError`, with `kind: "invalid"`,
529
+ the status of the response (200), and the `SyntaxError` as `cause`:
530
+ `Gemini's reply could not be read: it was not JSON (text/html). A proxy or gateway may have answered in its place.`
531
+ For an OpenAI-compatible endpoint the message starts "The model's reply …", and for Claude
532
+ "Claude's reply …"; without a content type, the part in parentheses is left out. It is not sent
533
+ again, by the loop or by a part read. 0.5.0 threw the `SyntaxError`, and a streamed Gemini
534
+ request that got such a page returned an empty reply. A reply of HTTP 200 whose body is empty is
535
+ a reply cut off on its way: kind `"unreachable"`, status 0,
536
+ `Gemini could not be reached (the reply was empty).` ("The model could not be reached …" and
537
+ "Claude could not be reached …" for the others), and it is sent again; 0.5.0 threw a
538
+ `SyntaxError` and did not.
539
+ **What to do:** if you test `error instanceof SyntaxError`, test
540
+ `error.cause instanceof SyntaxError` instead (kind `"invalid"`, status 200). Kind `"invalid"`
541
+ alone also covers every other request that the provider refused. See
542
+ [The kind of a model error](docs/guides/errors-and-reliability.md#the-kind-of-a-model-error).
543
+ - **An error inside a stream has the status, and the kind, that its type names.** On an
544
+ OpenAI-compatible endpoint, `context_length_exceeded` is HTTP 400, kind `"context_overflow"`
545
+ (the request is made smaller), `insufficient_quota` HTTP 429, kind `"quota"`, and any other the
546
+ server's failure, HTTP 500 unless it names another status, sent again when none of its text was
547
+ shown. On Claude, `invalid_request_error` is 400, `authentication_error` 401 (kind `"auth"`),
548
+ `billing_error` 402 (kind `"quota"`), `permission_error` 403, `not_found_error` 404 and
549
+ `request_too_large` 413, and a type the adapter does not know is the server's failure, 500, sent
550
+ again when none of the reply was shown. 0.5.0 gave all of these the stream's 200, and sent none
551
+ of them again; only Claude's `overloaded_error`, `rate_limit_error`, `api_error` and
552
+ `timeout_error` had a status of their own, as they still do. `OpenAiRequestError.code` holds the
553
+ code.
554
+ **What to do:** nothing, unless you show your own words by status.
555
+ - **A whole-file read tells the model why a model request failed by its kind, its HTTP status or
556
+ a connection code, never by the error's words.** Its result, its line in `onStep` and `steps`,
557
+ and `toolTurns` now say, for example, "Could not read any part of app.log: The model refused the
558
+ key or token it was sent (HTTP 401)." In 0.5.0 they carried the provider's message, which can
559
+ name a project, a host, a masked key, or a URL with a key in it. The same holds for a part that
560
+ could not be read among others, for a last step that failed (`notes_only`), and for every error
561
+ a `generate` throws, yours included. An error is told by its `kind` ("The model's quota has run
562
+ out", "The model was busy", with " (HTTP 429)" when it has a status), or by the kind that its
563
+ HTTP status (`status`, `statusCode` or `response.status`) and message give, as
564
+ `classifyModelError` works it out. A connection code such as `ECONNREFUSED` gives "The model
565
+ could not be reached.", a timeout (an error named `TimeoutError`, or undici's
566
+ `UND_ERR_HEADERS_TIMEOUT` and `UND_ERR_BODY_TIMEOUT`) "The model took too long to answer.", and
567
+ any other error, such as a plain `Error`, "The model request failed.". A part reader of the
568
+ package's that got a reply with no text is still told "The model returned no text (SAFETY).",
569
+ without the provider's reason when it is not a plain word, and an error of the document store
570
+ keeps its own message.
571
+ **What to do:** if you read the provider's words from the steps, log them in your own `fetch`,
572
+ adapter or `generate` instead. To give the model a specific reason, throw an error with a `kind`
573
+ or an HTTP `status`. See
574
+ [Failures inside tools](docs/guides/errors-and-reliability.md#failures-inside-tools).
575
+ - **A retry option that is not a finite number takes its default.** `retries`, `baseDelayMs` and
576
+ `maxDelayMs` (of the `retry` option and of `withRetry`) count as not set when they are `NaN`,
577
+ `Infinity`, `-Infinity` or not a number at all, such as a string from an environment variable.
578
+ They are then 3, 500 and 60,000. In 0.5.0, `retries: Infinity` sent a failing request again
579
+ without end, `-Infinity` counted as 0, and a string counted as the number in it. For `NaN`, see
580
+ **Fixed**.
581
+ **What to do:** nothing, unless you set one of them to `Infinity`, `-Infinity` or a string. Pass
582
+ a finite number: `retries: 0` to turn retries off, a larger `maxDelayMs` to take a long
583
+ `Retry-After`, and `Number(process.env.RETRIES)` rather than the string. See
584
+ [`RetryOptions`](docs/reference/errors-and-retries.md#retryoptions).
585
+ - **Gemini part reads send no temperature.** By default, the `generationConfig` of a part read in
586
+ a whole-file read, and of `createGeminiGenerateText`, is `{ maxOutputTokens }`. It was
587
+ `{ maxOutputTokens, temperature: 0.2 }`. Gemini 3.6 and later ignore the temperature, and Google
588
+ says later models will refuse it.
589
+ **What to do:** to keep it for an older model, pass
590
+ `analysisConfig: (maxOutputTokens) => ({ maxOutputTokens, temperature: 0.2 })` to `gemini()` or
591
+ `askGemini`, or a `generationConfig` that does the same to `createGeminiGenerateText`. See
592
+ [Whole-file reads in parts](docs/guides/vertex-and-gemini.md#whole-file-reads-in-parts).
593
+
594
+ What the model is sent, and what the loop does:
595
+
596
+ - **The frame around a file sent whole carries a mark, before the file's name.** Its two lines
597
+ were `--- Attached file: report.txt (text, 6 lines) ---` and
598
+ `--- End attached file: report.txt ---`. For every file sent whole, they are now
599
+ `--- Attached file [mark 1f0c3a9e]: "report.txt" (text, 6 lines; it ends only at the line with mark 1f0c3a9e) ---`
600
+ and `--- End attached file [mark 1f0c3a9e] ---`. The mark is eight hex digits made from the
601
+ document ID, which is made after the file's text was written, so a line of the file that copies
602
+ the end of the frame has no mark or a wrong one. The mark is not a secret (someone who knows a
603
+ document's ID can write its mark into a file uploaded later), and it does not make the model
604
+ obey. The name comes after the mark, quoted as JSON. A file that is not valid UTF-8 adds how it
605
+ was read after the count of lines (see **Changed**), and a file of one line says `1 line`. The
606
+ whole first line is
607
+ `--- Attached file [mark <8 hex digits>]: <name as JSON> (<format>, <lines> line|lines[, read as <encoding>[, <n> character|characters not valid in it, shown as �] | , <n> character|characters not valid UTF-8, shown as �]; it ends only at the line with mark <8 hex digits>) ---`,
608
+ with commas in the count of lines (`3,000`). The text between the two lines is the same as
609
+ before. The card of a file too large to send whole keeps its first line,
610
+ `--- Large attached file: app.log ---`.
611
+ **What to do:** if your code or tests look for these lines in `PreparedContext.blocks` or in the
612
+ requests, match the new form. To match the start of any of them, use `--- Attached file [mark `.
613
+ To find one file, look for `]: ` followed by its name as a JSON string (`JSON.stringify(name)`)
614
+ and ` (`: a quote or a backslash in the name is escaped. A test that compares the prompts of two
615
+ uploads must allow for the mark, as it allows for the document ID. See
616
+ [`PreparedContext`](docs/reference/library.md#preparedcontext) and
617
+ [The frame around a file](docs/security.md#the-frame-around-a-file).
618
+ - **The provider's prompt cache misses once after the upgrade, and then on each follow-up
619
+ question from the rounds of the question before it.** The tool guide in the system instruction
620
+ changed (see **Changed**), and so did the descriptions of `search_document` (next point) and
621
+ `analyze_whole_document`, the frame of every file sent whole, and, for a question without
622
+ `analyze_whole_document`, the cards.
623
+ The first request of each conversation after the upgrade therefore shares little or nothing of
624
+ its start with what 0.5.0 sent: its input costs what it costs without a cache (with Claude's
625
+ `cache_control`, a cache write). The mark of a document is the same in every request, so from
626
+ then on the cache reuses the files again. One miss stays: the tool rounds of an earlier
627
+ question are now sent without `tool_turns_left` (see below), so the first request of a
628
+ follow-up question differs from the requests of the question before it from that question's
629
+ first tool round on. Those rounds are billed at the full price once, in that request (with
630
+ Claude's `cache_control`, as a cache write); the cards, and the turns before those rounds, are
631
+ still read from the cache. While servers of both versions answer the same conversation, each
632
+ switch from one version to the other misses again.
633
+ **What to do:** nothing. During a rolling upgrade, keep a conversation on one version if you can
634
+ ([Servers of two versions](docs/guides/deployment.md#servers-of-two-versions)). See
635
+ [Prompt caching](docs/guides/costs-and-limits.md#prompt-caching).
636
+ - **A search in exact or regex mode shows the last matching line too.** When more lines match
637
+ than `max_results` (20 by default, 50 at most), `matches` holds the first `max_results` lines
638
+ and then the last matching line of the file: up to `max_results` + 1 entries. `note` says how
639
+ many are shown:
640
+ `21 of the 442 matching lines are shown: the first 20 and the last (line 15269). To see the ones in between, narrow the search.`
641
+ With `max_results` + 1 matches, every one is shown, and there is no note. A search with no more
642
+ matches than `max_results` is unchanged, unless its result is cut to the room it has. A cut
643
+ result, whatever its number of matches, drops matches from the end of the first ones, so that
644
+ the last one stays, and its note reads
645
+ `Showing 6 of the 442 matching lines to stay within the size limit: the first 5 and the last (line 15269). Narrow the query or read specific lines.`
646
+ In 0.5.0 that note counted the lines the result held, not the lines that matched
647
+ (`Showing 5 of 20 results to stay within the size limit. …`). A search that stopped early shows
648
+ no last line, since it did not reach it. Its note is now
649
+ `The scan stopped early; the total is a lower bound, and the last match in the file is not known.`,
650
+ and when such a result is cut too, the note of the cut follows that sentence. The `evidence` of
651
+ a search, and the stand-in that later replaces its result, list the lines of the last match too.
652
+ The description of the tool, which the model reads, now says that exact mode "finds the lines
653
+ that contain the text", and that "For exact and regex, total_matching_lines counts every
654
+ matching line, and the result shows the first max_results of them and the last one". It said
655
+ that exact mode "returns every line containing the text".
656
+ **What to do:** nothing, unless your code expects at most `max_results` entries in `matches`, or
657
+ your tests compare a search result whole. See
658
+ [`search_document`](docs/reference/tools.md#search_document).
659
+ - **A repeated call is answered with a pointer.** A call whose result is still in the
660
+ conversation in full is not run again: the same search, the same read, the same overview, or a
661
+ read of lines inside a read that is shown, in this question or in the stored tool rounds of an
662
+ earlier one. The model gets a pointer to that result. Its step reads
663
+ "Search app.log (exact) for “timeout” — already shown above", its result in `toolTurns` has
664
+ `already_shown: true` and a note, and it adds no entry to `evidence`. The same call made twice
665
+ in one turn is run once. A call is run again when the earlier result failed, was cut to its
666
+ room, was replaced by a stand-in, or came from a search that stopped early; when it is an exact
667
+ or regex search stored before 0.6.0 with more matches than it shows (it lacks the last match); and
668
+ when it is a read of one line from the rounds of an earlier question, since 0.5.0 cut a long line
669
+ to the room it had without saying so (no `text_cut`). With an adapter whose provider may clear
670
+ old tool results (`clearsToolResults`, under **New**), a call made again is run again.
671
+ **What to do:** if you parse `steps` or the lines of `onStep`, or expect one `evidence` entry
672
+ per call, allow for these. See
673
+ [Repeated calls in a follow-up](docs/guides/conversations.md#repeated-calls-in-a-follow-up).
674
+ - **The tool rounds of an earlier question are sent without `tool_turns_left`.** That count was of
675
+ the turns their own question had left, and a model could take a 0 there for its own. What
676
+ `toolTurns` stores is unchanged. `geminiToolTurns`, `openAiToolTurns` and `anthropicToolTurns`
677
+ leave the field out too, so a history kept in a provider's form gives the same request as one
678
+ kept as `toolTurns`; contents converted before 0.6.0 keep it.
679
+ **What to do:** nothing, unless your tests compare the output of a converter with the stored
680
+ `toolTurns`: leave `tool_turns_left` out of the expected value. See
681
+ [What `toolTurns` holds](docs/guides/conversations.md#what-toolturns-holds).
682
+ - **An empty or broken turn is asked for once more, at the cost of a request.** When the model's
683
+ first reply is empty, or holds a tool call that could not be read (Gemini's
684
+ `MALFORMED_FUNCTION_CALL` or `UNEXPECTED_TOOL_CALL`), it is asked once more with a short note;
685
+ 0.5.0 wrote the answer from the document cards alone, and it looked like any other. When the
686
+ request for the answer (the last one of the tool loop, sent with `toolChoice: "none"`) comes back
687
+ empty, or with a tool call the model was told not to make (`UNEXPECTED_TOOL_CALL`,
688
+ `MALFORMED_FUNCTION_CALL`, or calls from an adapter of your own), it is sent once more, with a
689
+ note at its end that is not kept:
690
+ `Your last reply had no text. No tool can be called in this reply: write the answer now, in text, from what is above.`
691
+ 0.5.0 ended such a question with `answered: false` and no text; a model that still writes no
692
+ text ends that way, one request later. A question makes at most two such second tries. Each is a
693
+ chat request: it counts toward `limits.requests` and takes a turn of `limits.toolTurns`, and the
694
+ one for the answer can be one request past `limits.toolTurns`. The answer is not asked for again
695
+ after a refusal, a filter, a reply cut off at the output limit with nothing in it, or once
696
+ `limits.requests` or `limits.inputTokens` is reached. With an explorer, the answering model gets
697
+ the note too.
698
+ **What to do:** if you set `limits.requests` or `limits.toolTurns` close to what a question
699
+ needs, add two. If a test fake of yours answers with nothing, or answers the answer's request
700
+ with a tool call, expect one more request and one more step: a fake with a fixed queue of
701
+ replies runs out. See [Empty or broken turns](docs/guides/errors-and-reliability.md#empty-or-broken-turns)
702
+ and [The limits of a question](docs/guides/costs-and-limits.md#the-limits-of-a-question).
703
+ - **Steps say more, on one line of plain text.** New steps say when a call was pointed to
704
+ ("— already shown above"), when a turn was asked for again ("The model's first reply was empty:
705
+ it was asked again", "The model's tool call could not be read: it was asked to send it again",
706
+ "The model's answer was empty: it was asked again", "The model called a tool instead of
707
+ answering: it was asked again for the answer"), and when a request was made smaller ("The
708
+ request was larger than the model takes: older tool results were shortened, and it was sent
709
+ again"). In the lines of `onStep`, `onActivity` and `result.steps`, a line break, a tab or another
710
+ control character in what the model sent becomes one space, together with the blanks around it,
711
+ and the characters that ingest drops from file text are dropped (see **Changed**), soft hyphens
712
+ and byte order marks included. "](" becomes "] (", so that a markdown link or picture in what the
713
+ model wrote stays text. A query is cut at 80 characters and a task at 100, never in the middle
714
+ of a character. A call to a tool that does
715
+ not exist is shown as `Call “do_magic” — failed: Unknown tool “do_magic”.`, with the name cut at
716
+ 64 characters, and its activity line is `Call “do_magic”…`; 0.5.0 started the step with the
717
+ whole name. The model gets `Unknown tool “do_magic”.`, and so does `files.tools().execute()`: it
718
+ was `Unknown tool do_magic.`. Steps still quote the model's words, HTML tags and web addresses
719
+ included.
720
+ **What to do:** if you parse steps or match the unknown-tool error, allow for these changes. Show
721
+ steps and activity lines as plain text, never as markdown or HTML. See
722
+ [What the library logs](docs/security.md#what-the-library-logs).
723
+ - **`anthropicToolTurns` and `openAiToolTurns` give a call without an ID a random one**
724
+ (`toolu_` or `call_` and 24 hex characters). Gemini's calls, for one, may come without an ID.
725
+ 0.5.0 numbered them from 1 on each call (`toolu_1_1`), so the stored rounds of two questions had
726
+ the same IDs, which Claude's Messages API refuses. A call that came with an ID keeps it. In
727
+ `anthropicToolTurns`, an ID the API would refuse is changed (see **Fixed**, The adapters).
728
+ **What to do:** nothing, unless you compare these IDs, or convert the same tool turns again for
729
+ each request: each conversion now gives new IDs. Convert once and store the messages when you
730
+ need the same IDs every time. See
731
+ [Histories in a provider's own form](docs/guides/conversations.md#histories-in-a-providers-own-form).
732
+ - **A question stopped while its adapter is being called ends with the signal's reason.** When
733
+ the signal aborts while the adapter is being called (from `onText`, say), `askWithFiles` now
734
+ throws the signal's reason, as it does for every other way of stopping, whatever the adapter
735
+ then does. When the adapter then failed with its own error, 0.5.0 threw that error (a 503, say);
736
+ when it answered anyway, 0.5.0 returned its reply as the answer, with `answered: true`. The
737
+ question also stops at once when the adapter does not look at the signal (see **Changed**).
738
+ **What to do:** if a test expects the adapter's error, or its reply, there, expect the signal's
739
+ reason.
740
+
741
+ Your own adapter or loop:
742
+
743
+ - **Your own adapter (optional).** An adapter written for 0.5.0 works as before. To get the new
744
+ recovery, set `ModelReply.finish` (`"malformed_call"` lets the loop ask again for a call that
745
+ could not be read), and throw a `ModelRequestError` from `send` and `generateText`. Its `kind`
746
+ is told from the status and the message, or you pass it: `"context_overflow"` makes the request
747
+ smaller (and a part read in halves), `"timeout"` with status 0 is sent again once, and
748
+ `"quota"` is not sent again. In your own loop, `withRetry` follows the same rules: an error of
749
+ kind `"quota"` or `"context_overflow"` is thrown at once, and one of kind `"timeout"` with
750
+ status 0 is sent again once (not at all when `retry.retries` is 0). `ModelAdapter.estimateTokens`
751
+ is now deprecated: the library never called it, and a later version may remove it. An adapter
752
+ that declares it still compiles; leave it out, and set `capabilities.tokenScale` for a tokenizer
753
+ that counts differently from the library's estimate. See
754
+ [Your own adapter or loop](docs/guides/own-adapter-and-loop.md).
755
+ - **If you call `parseSseJson` yourself.** It also reads the body of node-fetch and other async
756
+ iterables, and takes `{ onData, onDone, signal, maxEventLength }` (see **New**); calls written
757
+ for 0.5.0 compile as before. It now takes a CR alone for a line end, as the format allows (0.5.0
758
+ threw a `SyntaxError` on such a stream). An event of more than 64,000,000 characters ends the
759
+ stream with an `SseEventTooLongError`. And it no longer waits for the `cancel()` of the stream,
760
+ or the `return()` of an iterable, when it stops.
761
+ **What to do:** nothing, unless your stream can send one event of more than 64,000,000
762
+ characters: then pass a larger `maxEventLength`, or `Infinity`.
763
+
764
+ Tests:
765
+
766
+ - **Tests that compare exact output need new expectations.** A test that pins what the library
767
+ writes fails where 0.6.0 writes something else. The cases, each explained above or under
768
+ **Changed**:
769
+ - prompts: the tool guide, the description of `analyze_whole_document`, the frame of a file sent
770
+ whole, and the card (`1 line`, `1 page`, the line on how a file that is not valid UTF-8 was
771
+ read, and the line of a question without a whole-file read);
772
+ - searches: up to `max_results` + 1 `matches`, the `note`, the `evidence`, and the description
773
+ of `search_document`;
774
+ - steps: the new steps, the cleaned text, the unknown tool, and "1 matching line", "1 passage",
775
+ "1 part" and "1 more tool call in this turn was not run";
776
+ - tool results: `already_shown`, `text_cut`, `notes_only` and `answer_shortened`, and the IDs
777
+ listed with an unknown `document_id`;
778
+ - fakes: a model with a fixed queue of replies gets one more request after an empty reply, a call
779
+ that could not be read, or an answer without text, and none for a call repeated while its
780
+ result is shown; a fake `fetch` given to `gemini()`, `openAiCompatible()` or `anthropic()` gets
781
+ the request again when it never answers (after `firstByteTimeoutMs`; a second silence fails
782
+ with kind `"timeout"`), when its stream ends without its end mark (Gemini's `finishReason`, a
783
+ `finish_reason` or `[DONE]`, Claude's `stop_reason`) or is cut off, and when it answers HTTP 200
784
+ with an empty body, but fails at once when part of the reply was already shown; a streamed
785
+ reply that is not of type `text/event-stream` is read by what it holds; an adapter that fails,
786
+ or answers, after the question was stopped gives the signal's reason;
787
+ - errors: `error.cause instanceof SyntaxError` for a reply that is not JSON, the status and kind
788
+ of an error inside a stream, the kinds of `classifyModelError` (a request larger than a minute
789
+ allows is `{ kind: "context_overflow", limitTokens: 30000, requestedTokens: 45237 }`), and the
790
+ reasons of a whole-file read that failed;
791
+ - `geminiToolTurns`, `openAiToolTurns` and `anthropicToolTurns`: no `tool_turns_left`, and
792
+ random IDs for calls without one; `anthropic().capabilities` with context editing in `body`:
793
+ `clearsToolResults: true`; the body of a Gemini part read: no `temperature`;
794
+ - ingest: the stored text of a file with characters that show nothing, text that Word hides, a
795
+ hidden slide, or an older encoding; `owner: ""`; the 500 of an upload whose store fails; and
796
+ `MemoryDocumentStore.getMeta(id)`, a new object each time, so `toBe` between two calls fails.
797
+
798
+ **What to do:** update those expectations. Compare steps and evidence to the tools that ran
799
+ rather than to whole sentences, and leave the library's prompts out of what you compare whole,
800
+ as [What to assert](docs/guides/testing.md#what-to-assert) advises. The testing guide shows the
801
+ new forms in [Output that 0.6.0 changed](docs/guides/testing.md#output-that-060-changed).
802
+
803
+ If you ran main between 0.5.0 and 0.6.0:
804
+
805
+ - **Rounds that main stored, its ingest worker, and the kinds it gave.** Tool rounds that main
806
+ stored can hold pointers (`already_shown: true`). A pointer to a search that lacks its last
807
+ match, or to a read of one line from an earlier question, is now sent as the stand-in
808
+ `Not run then: it repeated an earlier call whose result was later dropped from the conversation to make room. Call it again if you need it.`,
809
+ and so is every pointer of an earlier question when the adapter sets `clearsToolResults`. The
810
+ ingest worker of main's deployment guide (`ingestInWorker`), which set the heap flag in
811
+ `NODE_OPTIONS`, did not hold its memory limit (see "One page of a PDF still holds the server"
812
+ above, under Uploads). Some kinds differ from main's: HTTP 402, Claude's credit balance and
813
+ spending limits, and a Vertex AI quota per day that only the message names are `"quota"` (they
814
+ were `"invalid"` or `"rate_limit"`); a request larger than the tokens a minute allow is
815
+ `"context_overflow"` (it was `"rate_limit"`); `insufficient_quota` inside an OpenAI-compatible
816
+ stream is 429 `"quota"` (it was 500 `"server"`, sent three more times); Claude's errors inside a
817
+ stream have their type's status (an `authentication_error` was `"invalid"`, and is `"auth"`);
818
+ and a streamed Gemini reply that is a page of HTML is `"invalid"` (it was `"unreachable"`, sent
819
+ three more times).
820
+ **What to do:** nothing for stored rounds. Replace an ingest worker with the child process of
821
+ `ingestInProcess` in [Deployment](docs/guides/deployment.md#uploads-and-ingest), and check code
822
+ that chooses by these kinds.
823
+
824
+ ### New: what you can add
825
+
826
+ The samples assume what your app already has: `files` from `createLargeFiles()`, `endpoint` from
827
+ `vertexAi()`, and the `documentIds` and `question` of the chat.
828
+
829
+ Errors and failed questions:
830
+
831
+ - **The kind of every model error.** `ModelRequestError` has `kind`, and so have the errors that
832
+ extend it (`GeminiRequestError`, `OpenAiRequestError`, `AnthropicRequestError`):
833
+ `"context_overflow"`, `"quota"`, `"rate_limit"`, `"timeout"`, `"unreachable"`, `"server"`,
834
+ `"auth"` or `"invalid"`. It is told from the status, the message and the provider's own code
835
+ (Gemini's `error.status` and `details`, OpenAI's `code`, Claude's `type`). For a request too
836
+ large for the model, `limitTokens` and `requestedTokens` are the provider's numbers when its
837
+ message gives them (the one Vertex AI sent in a live check gave only the limit).
838
+ `errorKindOf(error)` reads the kind of any error,
839
+ `classifyModelError(status, message, signals?)` tells it for errors of your own, and the types
840
+ are `ModelErrorKind` and `ModelErrorClass`. The constructor of each error class takes `kind`,
841
+ `code` and `details`. See
842
+ [The kind of a model error](docs/guides/errors-and-reliability.md#the-kind-of-a-model-error) and
843
+ [`ModelErrorKind`](docs/reference/errors-and-retries.md#modelerrorkind).
844
+ - **What a failed question found: `partialResultOf(error)`.** The question still throws the
845
+ provider's error. `partialResultOf(error)` gives what it had done until then, as an `AskResult`
846
+ with `answered: false`: its steps, evidence, tool rounds and usage. It is undefined for an error
847
+ thrown before the question started (a document that is missing). Exported from
848
+ `llm-large-files` and `llm-large-files/gemini`. See
849
+ [`partialResultOf(error)`](docs/reference/ask.md#partialresultoferror) and
850
+ [Keeping what a failed question found](docs/guides/errors-and-reliability.md#keeping-what-a-failed-question-found).
851
+
852
+ ```ts
853
+ import { errorKindOf, partialResultOf } from "llm-large-files";
854
+ import { askGemini } from "llm-large-files/gemini";
855
+
856
+ try {
857
+ const result = await askGemini({ files, endpoint, documentIds, messages: [{ role: "user", text: question }] });
858
+ console.log(result.text);
859
+ } catch (error) {
860
+ const partial = partialResultOf(error);
861
+ // Not an answer, but paid for: count its usage, and keep its tool rounds if you store them.
862
+ if (partial) console.log(partial.usage.requests, partial.usage.inputTokens, partial.toolTurns.length);
863
+ const kind = errorKindOf(error);
864
+ if (kind === "quota") console.log("The model's quota is used up. Try again later.");
865
+ else if (kind === "timeout" || kind === "rate_limit") console.log("The model did not answer. Try again in a minute.");
866
+ else throw error; // another kind, or not a model error (a missing document, a bug)
867
+ }
868
+ ```
869
+
870
+ ```ts
871
+ import { classifyModelError } from "llm-large-files";
872
+
873
+ classifyModelError(400, "This model's maximum context length is 128000 tokens. However, your messages resulted in 130512 tokens.");
874
+ // { kind: "context_overflow", limitTokens: 128000, requestedTokens: 130512 }
875
+ ```
876
+
877
+ - **Waits on a silent model: `firstByteTimeoutMs` and `idleTimeoutMs`**, on `askGemini`,
878
+ `gemini()`, `openAiCompatible()` and `anthropic()`. The defaults are the new exports
879
+ `DEFAULT_FIRST_BYTE_TIMEOUT_MS` (600,000) and `DEFAULT_IDLE_TIMEOUT_MS` (300,000); the type
880
+ `IdleWaits` holds the two options. See
881
+ [Waits on a silent model](docs/guides/errors-and-reliability.md#waits-on-a-silent-model) and
882
+ [`IdleWaits`](docs/reference/errors-and-retries.md#idlewaits).
883
+
884
+ ```ts
885
+ import { askGemini } from "llm-large-files/gemini";
886
+ import { openAiCompatible } from "llm-large-files/openai";
887
+
888
+ // A chat that streams to a user: give up sooner than the defaults.
889
+ const result = await askGemini({
890
+ files,
891
+ endpoint,
892
+ documentIds,
893
+ messages: [{ role: "user", text: question }],
894
+ firstByteTimeoutMs: 180_000, // the first piece of a reply within 3 minutes
895
+ idleTimeoutMs: 60_000, // then no pause longer than 1 minute
896
+ onText: (delta) => process.stdout.write(delta),
897
+ });
898
+
899
+ // A local model that reads a long prompt slowly: wait for its first piece without end.
900
+ const local = openAiCompatible({ baseUrl: "http://localhost:8000/v1", model: "local-model", firstByteTimeoutMs: 0 });
901
+ ```
902
+
903
+ - **`RetryNotice`**: the type of what `withRetry` passes to `onRetry`: `error`, `attempt` (the
904
+ number of the retry to come) and `delayMs` (the wait). 0.5.0 passed the same notice but did not
905
+ export its type. See
906
+ [Errors, retries and streams](docs/reference/errors-and-retries.md#retrynotice).
907
+ - **`OpenAiRequestError.param` and `.code`**: the server's `error.param` (`"max_tokens"`) and
908
+ `error.code` (`"unsupported_parameter"`, `"context_length_exceeded"`). See
909
+ [`OpenAiRequestError`](docs/reference/openai.md#openairequesterror).
910
+
911
+ Your own adapter or loop:
912
+
913
+ - **`ModelReply.finish`**: how a reply ended, in terms every adapter maps its own to:
914
+ `"complete"`, `"cut"` (at the output limit, or Claude's full window), `"filtered"` (by the
915
+ provider's safety filters) or `"malformed_call"` (a tool call that could not be read: Gemini's
916
+ `MALFORMED_FUNCTION_CALL` and `UNEXPECTED_TOOL_CALL`). The three adapters set it. See
917
+ [`ModelReply`](docs/reference/ask.md#modelreply) and
918
+ [How the reply ended](docs/guides/own-adapter-and-loop.md#how-the-reply-ended-finish).
919
+ - **`ModelCapabilities.clearsToolResults`**: for an adapter whose provider may clear old tool
920
+ results on its side. A call made again is then run again, not answered with a pointer to a
921
+ result the model may no longer have, and the pointers in stored rounds become stand-ins that say
922
+ to call again. `anthropic()` sets it when `body.context_management` has an edit that clears tool
923
+ uses (`clear_tool_uses_…`) or compacts the conversation (`compact_…`). The loop still counts
924
+ every result as sent, so its room runs out at the same point as without context editing. An
925
+ adapter of your own sets it itself. See [`ModelCapabilities`](docs/reference/ask.md#modelcapabilities).
926
+ - **`ToolCallLimits.maxRequests`**: the model requests a whole-file read may make. It does not
927
+ stop the read: a part the model refuses as too large is read as two halves only while it allows.
928
+ `askWithFiles` passes the read's own requests and a share of what the question has left of
929
+ `limits.requests`; in your own loop, pass it to `executeWithFiles`. See
930
+ [Tools](docs/reference/tools.md#toolcalllimits).
931
+ - **`PrepareOptions.wholeDocumentAnalysis`**: whether your tool set has `analyze_whole_document`.
932
+ Defaults to `true`. In your own loop, pass `wholeDocumentAnalysis: false` to `files.prepare()`
933
+ when you call `files.tools()` without `generate`: the tool guide then does not name the tool,
934
+ and the cards do not offer a whole-file read. See
935
+ [The library and its documents](docs/reference/library.md#prepareoptions).
936
+ - **`SseHooks`**: the second argument of `parseSseJson`: `onData` (bytes arrived, keep-alives
937
+ included), `onDone` (`data: [DONE]` arrived), `signal`, and `maxEventLength`, the most
938
+ characters one event may hold, counted on its data. It defaults to 64,000,000; `Infinity` sets
939
+ no limit. A longer event ends the stream with an `SseEventTooLongError`
940
+ (`An event of the stream held more than 64,000,000 characters.`), whose `limit` holds the limit.
941
+ The class is exported from `llm-large-files` and `llm-large-files/gemini`. The same event would
942
+ come again, so an adapter of your own should not send the request again for it. See
943
+ [`SseHooks`](docs/reference/errors-and-retries.md#ssehooks).
944
+
945
+ Uploads:
946
+
947
+ - **`maxTextBytes`**: the most text kept from one file, in UTF-8 bytes. Defaults to
948
+ `DEFAULT_MAX_TEXT_BYTES`, 100 MB, or to `maxUploadBytes` when that is larger. The PDF, DOCX and
949
+ PPTX extractors refuse a file as soon as its text passes it (a PDF page by page), and `ingest`
950
+ refuses a larger text from any other extractor, yours included. See
951
+ [`LargeFilesOptions`](docs/reference/library.md#largefilesoptions).
952
+ - **`maxPdfPages`**: the most pages read from one PDF. Defaults to `DEFAULT_MAX_PDF_PAGES`, 5,000.
953
+ A PDF with more is refused before any page is read. See
954
+ [the library reference](docs/reference/library.md#default_max_pdf_pages).
955
+ - **`ingestTimeoutMs`**: the most time one `ingest` may take. Defaults to
956
+ `DEFAULT_INGEST_TIMEOUT_MS`, 120,000 (2 minutes); 0 sets no limit, and so does a value past
957
+ what a timer can wait (2,147,483,647 ms, 24.8 days). See
958
+ [`LargeFilesOptions`](docs/reference/library.md#largefilesoptions).
959
+ - **`IngestInput.signal`**: stops an ingest, for example when the uploader goes away. `ingest`
960
+ throws the signal's `reason` and stores nothing. The PDF, DOCX and PPTX extractors stop between
961
+ pages and pieces, and the text extractor between the steps of a file that is not valid UTF-8.
962
+ `createDocumentHandlers` passes one that aborts when the client closes the connection. See
963
+ [`IngestInput`](docs/reference/library.md#ingestinput).
964
+ - **`ExtractInput.signal`, `ExtractInput.maxTextBytes` and `ExtractInput.maxPages`**: the signal
965
+ of the ingest (aborted at `ingestTimeoutMs` or by `IngestInput.signal`) and the two limits, for
966
+ an extractor of your own to honour. See
967
+ [Custom extractors](docs/guides/pdfs.md#custom-extractors).
968
+ - **`createPdfExtractor({ checkPages: false })`** turns the page check off. With
969
+ `pictures: false` too, PDFs are not read with `@cantoo/pdf-lib` at ingest. See
970
+ [`PdfExtractorOptions`](docs/reference/library.md#pdfextractoroptions).
971
+ - **`DocumentMeta.encoding` and `DocumentMeta.replacedCharacters`**, and the same two fields of
972
+ `DocumentSummary` and `ExtractedText`: how a text file that is not valid UTF-8 was read.
973
+ `encoding` is the older encoding the file was read in, as TextDecoder names it
974
+ (`"windows-1255"`); lines of the file that are valid UTF-8 were read as UTF-8 all the same.
975
+ `replacedCharacters` is the number of characters that were not valid in the encoding the file
976
+ was read in (UTF-8, or `encoding`), each stored as U+FFFD. Both are absent for valid UTF-8, for
977
+ UTF-16, PDF, DOCX and PPTX, and on documents stored before 0.6.0; `encoding` is absent too for a
978
+ file read as UTF-8 with characters that are not valid. `toDocumentSummary` passes them on, so
979
+ the upload route of `createDocumentHandlers` answers with them. An extractor of your own may
980
+ report them in `ExtractedText`: `encoding` is kept when it is a name, such as `iso-8859-2`, other
981
+ than UTF-8 or UTF-16, and `replacedCharacters` when it is a whole number above 0. See
982
+ [`DocumentMeta`](docs/reference/library.md#documentmeta).
983
+
984
+ ```ts
985
+ import type { ServerResponse } from "node:http";
986
+ import { createLargeFiles, FileDocumentStore, type DocumentMeta } from "llm-large-files";
987
+
988
+ const files = createLargeFiles({
989
+ store: new FileDocumentStore("./data/large-files"),
990
+ maxTextBytes: 50 * 1024 * 1024, // keep at most 50 MB of text from one file
991
+ maxPdfPages: 2_000, // refuse a longer PDF before reading a page of it
992
+ ingestTimeoutMs: 60_000, // give up on a file after one minute
993
+ });
994
+
995
+ // In an upload route of your own: stop reading the file when the uploader goes away.
996
+ async function ingestUpload(response: ServerResponse, name: string, bytes: Uint8Array, owner: string): Promise<DocumentMeta> {
997
+ const uploaderLeft = new AbortController();
998
+ response.on("close", () => uploaderLeft.abort(new Error("The upload was cancelled.")));
999
+ const meta = await files.ingest({ name, bytes, owner, signal: uploaderLeft.signal });
1000
+ // Tell the user how a file that was not in UTF-8 was read.
1001
+ if (meta.encoding) console.log(`${meta.name} was read as ${meta.encoding}.`);
1002
+ if (meta.replacedCharacters) console.log(`${meta.replacedCharacters} characters of ${meta.name} show as �.`);
1003
+ return meta;
1004
+ }
1005
+ ```
1006
+
1007
+ ### Changed: what works differently
1008
+
1009
+ Besides the points under **Upgrading**:
1010
+
1011
+ The tool loop:
1012
+
1013
+ - **A request too large for the model is made smaller and sent again**, where 0.5.0 failed the
1014
+ question. The loop takes the provider's count and window for the rest of the question,
1015
+ replaces older tool results with short stand-ins (the latest round too, if it must), and sends
1016
+ the request again, at most twice a question. When the first requests are too large before any
1017
+ tool ran, the documents are planned again, once, for a smaller window worked out from the
1018
+ provider's numbers, or 7/10 of the window assumed when it gives none. Vertex AI's message names
1019
+ 1,048,576 tokens and no count: with the default window of 1,000,000, the documents are planned
1020
+ for 838,860. What the first try paid for, and the tool turns it took, are counted. When Claude is
1021
+ one of the models, nothing is shortened (its conversation may only grow), so only the second
1022
+ plan applies. The wordings known include those of Text Generation Inference and Together, LM
1023
+ Studio, Amazon Bedrock and vLLM, besides Gemini's, OpenAI's and Claude's. See
1024
+ [A request too large for the model](docs/how-it-works.md#a-request-too-large-for-the-model).
1025
+ - **Two searches in a row that failed in the same mode** get a hint added to the error: after two
1026
+ regex searches, to try exact or keywords mode; after two of another mode, to check the arguments
1027
+ or answer from what the model has.
1028
+ - **An unknown `document_id`** is answered with the IDs the model may use, and their file names
1029
+ (up to 20). An ID longer than 64 characters is quoted cut, in the error and in its step.
1030
+ - **The tool guide, and the description of `analyze_whole_document`, send counting and listing to
1031
+ exact search.** Both sent "every occurrence" to `analyze_whole_document`, which missed items in
1032
+ our live tests (492 of 1,200; 91 of 120), while `search_document` in exact or regex mode gives
1033
+ an exact `total_matching_lines`. The whole-file read is now for what needs meaning: a summary, a
1034
+ timeline, items judged one by one. See [The tool guide](docs/reference/tools.md#the-tool-guide)
1035
+ and [`analyze_whole_document`](docs/reference/tools.md#analyze_whole_document).
1036
+ - **In `askWithFiles` and `askGemini`, the tool guide names `analyze_whole_document`, and the
1037
+ cards offer a whole-file read, only when the question has the tool.** With
1038
+ `wholeDocumentAnalysis: false`, or a model that explores without `generateText`, they still
1039
+ offered a whole-file read when a file was small enough for one, and a model that called it was
1040
+ answered "Unknown tool analyze_whole_document.". Each card now says "Use the document tools to
1041
+ search it and to read line ranges.", and the guide leaves the tool's line out. In your own loop,
1042
+ pass `wholeDocumentAnalysis: false` to `files.prepare()` for the same (see **New**). See
1043
+ [Tools](docs/reference/tools.md#which-tools-are-offered).
1044
+ - **A part of a whole-file read that the model refuses as too large is read as two halves**,
1045
+ while `maxMapChunks` and the requests the question has left allow it.
1046
+ - **A part that the provider stopped before its end is said to be incomplete**, as one cut off at
1047
+ the output limit is: Gemini's `SAFETY` and its other filter reasons, OpenAI's `content_filter`,
1048
+ Claude's `refusal`, and Claude's `model_context_window_exceeded` (its window was full).
1049
+ - **Tool results have new fields**: `already_shown` (a pointer), `text_cut` (a `read_document`
1050
+ whose text was cut to its room), and, on a whole-file read, `notes_only` and
1051
+ `answer_shortened` (see **Fixed**). The step of a whole-file read that returned its notes ends
1052
+ in ", notes only". See [Tools](docs/reference/tools.md).
1053
+ - **A question stops when its signal aborts, even with an adapter that does not.** The loop no
1054
+ longer waits for an adapter (or a part reader of a whole-file read) that does not look at
1055
+ `signal`. With 0.5.0, an adapter whose request never ended held the question for good after an
1056
+ abort. `askWithFiles` now throws the signal's reason at once (310 ms after an abort at 300 ms),
1057
+ also when `onText` stopped it or when it was stopped between two requests, with
1058
+ `partialResultOf`; nothing is sent after the stop, no further part of a whole-file read either;
1059
+ and text that such an adapter sends later is not shown. `partialResultOf(error).usage` is what
1060
+ was counted when the question stopped: a request still running then may be billed by the
1061
+ provider, and is not counted. See [Cancelling](docs/guides/web-app.md#cancelling).
1062
+ - **`geminiFunctionResponses` returns a `GeminiContent & { role: "user" }`, and
1063
+ `geminiFunctionResponseTurns` an array of them**, which go into a `GeminiContent[]` without a
1064
+ cast. Their parts were typed `unknown[]` (see **Upgrading**). See
1065
+ [`llm-large-files/gemini`](docs/reference/gemini.md#geminifunctionresponsescalls).
1066
+
1067
+ Ingest:
1068
+
1069
+ - **Ingest lets other requests run while it reads a file.** Each step works in slices of about
1070
+ 12 ms, with a pause for other requests between two slices: the PDF extractor between pages, the
1071
+ DOCX and PPTX extractors as they unpack, the text extractor as it reads a file that is not valid
1072
+ UTF-8, and then `ingest` as it cleans the text, measures it, and builds the outline, the log
1073
+ profile and the line index. Ingests that run at once take turns, one slice each. Picture marks
1074
+ pause every 12 ms between pages, and their limit of 5 s counts only the work, not the pauses. An
1075
+ ingest of a 99 MB log takes 1.9 s, as before, now in slices.
1076
+ - **`createDocumentHandlers` stops reading an upload when the client goes away.** Its upload
1077
+ handler passes `IngestInput.signal`, aborted when the connection closes before the answer is
1078
+ sent: nothing is stored.
1079
+ - **`ingest` stops waiting for an extractor** when the ingest's signal aborts (`ingestTimeoutMs`,
1080
+ or `IngestInput.signal`), whether or not the extractor looks at the signal.
1081
+ - **DOCX and PPTX take memory by their text, not by their XML.** Each paragraph becomes one string
1082
+ when it closes, and an empty paragraph is dropped. Text is counted as it reads, not as the XML
1083
+ writes it (`&amp;` is one character).
1084
+ - **`view_pages` and picture marks pause by time.** `@cantoo/pdf-lib` reads the whole file into
1085
+ objects first, and on its own pauses for other requests after a count of objects: 0.5.0 used
1086
+ 4,000, which took 0.5 to 0.8 s in a large file, while a file of fewer objects never paused. It
1087
+ now pauses after every 12 ms of work (up to 40 ms on Windows, where a pause takes about 15 ms).
1088
+ Measured on Windows with Node 24: a file of 4,000 large arrays held the event loop for 28 to
1089
+ 32 ms at a time, and a 2,000-page PDF 19 to 38 ms. A whole read takes 0.91 to 0.96 s for a file
1090
+ of 61,000 small objects and 1.35 to 1.43 s for one of large objects, against 1.65 to 1.87 s and
1091
+ 1.13 to 1.22 s with a pause every 500 objects; 0.5.0's pause every 4,000 was not timed this way.
1092
+ Your app's own use of `@cantoo/pdf-lib` is not changed.
1093
+ - **The model is told how a text file that is not valid UTF-8 was read.** The card of a large
1094
+ file gets one more line:
1095
+ `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.`
1096
+ When bytes of the file are not in that encoding, the line goes on:
1097
+ ` 1 character of it was not valid in windows-1255, and shows as �.` For a file read as UTF-8
1098
+ with characters that are not valid, the line is
1099
+ `3 characters of this file were not valid UTF-8, and show as �.`
1100
+ The first line of the frame of a file sent whole says the same in short, after the count of
1101
+ lines: `, read as windows-1255`, `, read as windows-1255, 1 character not valid in it, shown as �`,
1102
+ or `, 3 characters not valid UTF-8, shown as �`. A file that is valid UTF-8 or UTF-16 gets no
1103
+ such line. See [The card](docs/how-it-works.md#the-card).
1104
+ - **A text file that is not valid UTF-8 is read in slices,** with pauses for other requests, and
1105
+ it stops when the ingest's signal aborts. Reading it takes about twice as long as 0.5.0's decode,
1106
+ which gave U+FFFD: 0.27 to 0.28 s against 0.11 to 0.16 s for a 30 MB CSV in windows-1255, in
1107
+ steps of 15 ms at most. A file whose lines take turns between UTF-8 and an older encoding takes
1108
+ longer, the shorter its lines are: for 30 MB, 0.50 to 0.53 s in lines of 100 bytes, and 2.1 to
1109
+ 2.2 s in lines of one letter (Node 24, Windows). See
1110
+ [Text encodings](docs/guides/pdfs.md#text-encodings).
1111
+ - **Ingest removes characters that show nothing** from the text: control characters
1112
+ U+0080-U+009F, which 0.5.0 kept (a U+0085 can become a line break instead; see the next point),
1113
+ and an escape sequence that starts with U+009B, such as `\u009b31m`, whole (0.5.0 stored
1114
+ `x\u009b31mERROR` as it was; it is now `xERROR`), but for a U+009B right after a character of
1115
+ U+0080-U+00FF, which is the end of a letter of UTF-8 read as Latin-1 ("ś" is C5 9B) and goes
1116
+ alone ("Coś? Tak" keeps its "? Tak"); Unicode tag characters
1117
+ (U+E0000-U+E007F); the text-direction controls that reorder what a person sees (U+202A-U+202E,
1118
+ U+2066-U+2069); the zero-width space, the word joiner and the invisible operators (U+200B,
1119
+ U+2060-U+2064); the deprecated format characters (U+206A-U+206F); a byte order mark inside the
1120
+ text; and the soft hyphen, except at the end of a line. Kept: the marks right-to-left text needs
1121
+ (U+200E, U+200F, U+061C), zero-width joiners and non-joiners (emoji, Persian), variation
1122
+ selectors, and the flags of England, Scotland and Wales; other flags written with tag characters,
1123
+ such as Texas, keep only the black flag. A file name loses the same characters, but its control
1124
+ characters and text-direction controls become a space, as in 0.5.0. Of these
1125
+ removals, two move lines: in a text with no line feed, where U+0085 ends lines, and after a line
1126
+ of more than 2,000 characters that lost some of them, which can now be cut into fewer lines;
1127
+ hidden text in a DOCX moves lines too (below). A file read as 0.5.0 read it that holds none of
1128
+ these characters, and has no hidden text or hidden slide, is stored as before, byte for byte (25
1129
+ inputs compared, 12 PDFs among them). Cleaning takes 2 to 7% longer on an ASCII log, and 10 to
1130
+ 20% on Hebrew in UTF-8; a whole ingest did not take longer beyond the spread of runs. See
1131
+ [Characters that show nothing](docs/security.md#characters-that-show-nothing).
1132
+ - **U+0085 ends a line in a text that has no other line break.** Some files end each record with
1133
+ U+0085 (NEXT LINE) and contain no line feed, such as z/OS data converted to UTF-8 with iconv
1134
+ (IBM-1047). 0.5.0 stored such a file as one line, with the U+0085 characters in it. Each record
1135
+ is now a line of its own, and an empty record is dropped. A record that ends in a character of
1136
+ U+0080-U+00FF, such as É, ° or £, still runs into the next one: there a U+0085 is taken for the
1137
+ last byte of a UTF-8 letter read as Latin-1 ("ą" is C4 85), and removed. A file of one line,
1138
+ such as minified JSON, has no other line break either, so a U+0085 inside one of its strings
1139
+ becomes a line break too. In a text with other line breaks, a U+0085 is removed with the other
1140
+ C1 control characters. The same export in ISO-8859-1, with a byte 0x85 at the end of each
1141
+ record, is read as windows-1252, where 0x85 is "…", and stays one long line, cut every 2,000
1142
+ characters: convert such a file to UTF-8 instead.
1143
+ - **Text that Word hides is marked.** The text of a run hidden in Word (`<w:vanish/>`) was stored
1144
+ as ordinary text. It now comes after the text of its paragraph that shows, and each of its lines
1145
+ starts with `[Hidden text, not shown in the document]`, so that the model can tell it from what
1146
+ a reader sees; a line break in it starts a new marked line, and a line longer than about 1,950
1147
+ characters is cut into pieces, each marked. The marks count toward `maxTextBytes` and the 32
1148
+ million characters of a DOCX. The mark is a hint, not a filter: text hidden through a style,
1149
+ white or 1-point text, and a few rarer forms are read as ordinary text, and a document's own
1150
+ text can write the mark. See
1151
+ [Hidden text in Word and PowerPoint](docs/security.md#hidden-text-in-word-and-powerpoint).
1152
+ - **A hidden slide says so.** The heading of a slide that the slide show skips (`show="0"`) reads
1153
+ `## Slide 2 (hidden, not shown in the slide show)`. Its text is kept. Shapes hidden on a slide
1154
+ that shows are read as ordinary text. See [DOCX and PPTX](docs/guides/pdfs.md#docx-and-pptx).
1155
+ - **`MemoryDocumentStore` copies the metadata** it is given and the metadata it hands out, as a
1156
+ store that writes it somewhere does. `getOriginal` still returns the kept bytes themselves: treat
1157
+ them as read-only. See [`MemoryDocumentStore`](docs/reference/library.md#memorydocumentstore).
1158
+
1159
+ The adapters:
1160
+
1161
+ - **A request sent again after its reply was cut off on its way says so.** `onActivity` gets
1162
+ "The model's reply was cut off on its way. Trying again…" for a stream that closed before its
1163
+ end, a connection that failed once the reply had begun, or a reply of HTTP 200 that came empty.
1164
+ "The model could not be reached. Trying again…" stays for a connection that failed before any
1165
+ reply.
1166
+ - **A reply asked for as a stream is read by what it holds when its content type is not
1167
+ `text/event-stream`.** It is read as events when it starts like them (a field such as `data:`,
1168
+ or a comment), and as JSON when it starts with `{` or `[`. A body that starts with more than
1169
+ 65,536 characters of white space is read as JSON, whatever follows it. A gateway that streams
1170
+ under `application/octet-stream`, or under no type, failed with a `SyntaxError` on the
1171
+ OpenAI-compatible and Claude adapters. Gemini's chunks in a list, as it sends them without
1172
+ `alt=sse`, are read too. See
1173
+ [A stream cut off](docs/guides/errors-and-reliability.md#a-stream-cut-off).
1174
+ - **Claude: `x-should-retry: false` is followed.** A request that the API says not to try again is
1175
+ not sent again, whatever its status, as Anthropic's own SDKs do.
261
1176
 
262
1177
  ### Fixed
263
1178
 
264
- - **Token estimates were far too low for logs and data files.** `estimateTokens` assumed 4
265
- characters per token, which holds for prose only: Gemini counts about one token per digit. A
266
- service log was estimated at 37% of its real size and a CSV of numbers at 26%, so such files were
267
- sent whole, and split into parts, at about three times the configured budget. The estimate now
268
- prices each kind of character and was fitted to Gemini's `countTokens` on 60 texts; it lands
269
- between 0.98 and 1.7 times the real count. Documents already in a store keep the estimate they
270
- were ingested with until they expire.
271
- - **A regex search could freeze the server.** Patterns such as `((a+))+$` and `(a|a)+$` passed the
272
- nested-quantifier check and never finished on a 40-character line; the 3-second limit was only
273
- checked between lines. Regex scans now run under a hard time limit that interrupts a match in
274
- progress.
275
- - **`askGemini` could return a remark instead of an answer.** If the model wrote "Let me search…"
276
- with a tool call and its next turn came back empty (cut off, or a malformed tool call), that
277
- remark was returned as the answer. The tool-free request is now sent whenever the model's last
278
- turn has no text.
279
- - **A blocked prompt resolved as an empty answer with no reason.** The result now has
280
- `answered: false` and `blockReason`.
281
- - **One model request was wasted when the tool turns ran out.** The last request was sent with
282
- tools, its calls were discarded, and then another was sent without tools. `askGemini` now goes
283
- straight to the tool-free request, so it never makes more than `maxToolTurns` requests.
284
- - **Case-insensitive search found nothing in a file containing "İ"** (U+0130), in exact and
285
- keyword mode: the whole file silently fell back to case-sensitive matching.
286
- - **Coloured logs lost their profile.** Only the ESC byte of a terminal colour code was removed,
287
- leaving `[31mERROR[0m`, which no longer matched as a level. Whole escape sequences are removed.
288
- - **Compressed files were accepted as text.** A `.gz` log became a document of garbage. Gzip and
289
- ZIP files are refused with a message that says what to do, and other binary files without zero
290
- bytes are now detected too.
291
- - **Ingest failed with "Maximum call stack size exceeded"** on files with a few hundred thousand
292
- short heading-like lines.
293
- - **A file name could add lines to the prompt.** Control characters, line breaks, and
294
- text-direction overrides are removed from names at ingest, and names are quoted in the system
295
- instruction.
296
- - **Whole-document reads hid that they were incomplete.** When part notes or the final answer
297
- reach the output limit, the tool result now says so (`notes_cut_short`, `answer_cut_short`, and a
298
- `note` telling the model to say so and to use exact search for complete lists). If no part can be
299
- read, the tool returns an error instead of an answer written from nothing.
300
- - `read_document` reported a line range past the end of the file when no end line was given.
301
-
302
- - **Words of right-to-left text in a PDF were glued together** when the file stores them piece by
303
- piece (as Word does): `יתרת סגירה4,167.90`. pdf.js adds the space only between pieces that run
304
- left to right. The space is now added from the positions.
305
-
306
- ### Changed
307
-
308
- - **PDF tables are rebuilt.** A PDF stores text at positions, not tables. In file order, a row
309
- with an empty cell reads like a row without that column, so a model takes the next value for the
310
- missing one. The PDF extractor now finds tables by the position of their text and writes each
311
- row as `| cell | cell | | cell |`. In a live test (`gemini-3.5-flash-lite`, 110 questions about
312
- single cells of seven PDFs made by Word and Chrome), 44 answers were right from the old text and
313
- 110 from the new. It also handles tables in one column of a two-column page, right-to-left and
314
- sideways tables, headings that span columns, and wrapped cells; text that is not a table is left
315
- as it was. Two-column tables are left as text. See
316
- [PDF tables](docs/configuration.md#pdf-tables) for the limits.
317
- `createPdfExtractor({ tables: false })` gives the previous text. Documents already in a store
318
- keep the text they were ingested with.
319
- - **A PDF page without any text is marked** `[No text on this page. It may be a scan, a photo, or a
320
- chart.]` instead of being left empty, so the model can say that it cannot see the page.
321
- - **Documents are placed at the start of the first user turn**, not appended to the latest one.
322
- The document then stays in the same place as the conversation grows, so Gemini's prompt cache
323
- reuses it: in a live test, a follow-up question about a 53,000-token document had 96% of its
324
- input served from cache, against 0% before. Pass `documentPlacement: "last"` to `askGemini` for
325
- the previous layout.
326
- - `maxToolTurns` is now the most requests one question can make, counting the answer. Tools still
327
- run in at most `maxToolTurns - 1` of them, as before.
328
-
329
- ### Added
330
-
331
- - `createPdfExtractor({ tables })`, exported from the main entry point.
332
- - `AskGeminiResult.answered` and `AskGeminiResult.blockReason`.
333
- - `GenerateText` requests carry an optional `onTruncated` callback; `createGeminiGenerateText`
334
- calls it when Gemini stops at `MAX_TOKENS`.
335
-
336
- ## [0.1.0] - 2026-11-06
337
-
338
- First release, extracted from the large-file support in the Gemini Prep chatbot.
339
-
340
- ### Added
341
-
342
- - `createLargeFiles`: ingest, per-request planning against a token *and* byte budget, summary
343
- cards, and scoped tools (`search_document`, `read_document`, `get_document_overview`,
344
- `analyze_whole_document`).
345
- - Extraction for text, Markdown, logs (UTF-8/UTF-16), JSON/JSONL, CSV/TSV, DOCX and PPTX (optional
346
- `jszip`), and PDF (optional `unpdf`).
347
- - Log profiles (levels, time range, most frequent error shapes) and outlines for books and documents.
348
- - Map-reduce over whole documents with parallel part reads, a retry, and rounds of merging.
349
- - `MemoryDocumentStore` and `FileDocumentStore` with expiry.
350
- - Document owners: documents are private to the user who uploaded them.
351
- - `llm-large-files/gemini`: `askGemini` (streaming tool loop that always ends in an answer),
352
- `geminiApi` and `vertexAi` endpoints, and lower-level adapters.
353
- - `llm-large-files/node`: upload, get, and delete handlers for any Node HTTP server.
1179
+ Uploads you do not trust (the numbers before were measured on main at 5157e7f, whose ingest, PDF
1180
+ and Office code is that of 0.5.0):
1181
+
1182
+ - **A DOCX of 1.5 MB no longer stops a server with a heap of 512 MB.** It held 120 MB of empty
1183
+ paragraphs, each of which 0.5.0 kept until the end of the file: the process ran out of memory
1184
+ and stopped, and every answer streaming on it with it. The same file is now refused
1185
+ ("padded.docx did not contain any text.") in 3.0 to 3.2 s, with the process at 115 MB. A DOCX
1186
+ of 3 MB that unpacks to 1,000 MB of XML, which stopped the same server, is refused at its
1187
+ millionth paragraph in 0.9 s, at 165 MB.
1188
+ - **A DOCX of many parts, or with a list of parts built to exhaust JSZip, no longer stops the
1189
+ server.** 0.5.0 had no limit on the parts of an Office file: 300,000 empty parts took over
1190
+ 500 MB in JSZip, and a DOCX of 88 MB with a million parts ran a heap of 1.5 GB out of memory.
1191
+ The parts are now counted, and the list read, before JSZip reads it, as JSZip will read it.
1192
+ Unicode Path fields that ran over the records after them ran a heap of 256 MB out of memory from
1193
+ a DOCX of 0.17 MB, and a ZIP64 end record of a file of 636 bytes held the process until it was
1194
+ killed. Such files are refused in 40 to 90 ms, with the heap at 8 to 9 MB. Real files are read
1195
+ as before (245 ZIP files of Office, Java and other programs compared), and a DOCX just under
1196
+ every limit at once is read in 0.46 to 0.48 s. See [Measurements](docs/measurements.md#the-server).
1197
+ - **A PDF of a few KB no longer stores 100 MB of text, or holds the server for minutes.** These
1198
+ files are now refused, each in under 0.3 s:
1199
+ - a page tree that lists one dense page 150 times (3 KB, 107 MB of text) or 600 times (6 KB:
1200
+ it held the event loop for 205 s with a heap of 1.5 GB, and ran a heap of 512 MB out of
1201
+ memory);
1202
+ - 140 pages that all paint one dense content stream (23 KB, 99.5 MB of text), and 60 pages that
1203
+ all show one stream of 4 MB (25 KB, 1.3 s a page, 38 s in all);
1204
+ - a page that paints a form that paints the next one 50 or 100 times, three levels deep (3 KB,
1205
+ 13 s, 350 to 380 MB; 4 KB, about 100 s), files of 2 to 21 KB built the same way, 2 to 6 levels
1206
+ deep (17 s to 2 minutes), eight forms that each paint all eight (6 s), and forms painted from
1207
+ content that only pdf.js could decode (10 s);
1208
+ - a page that runs 160 MB of text operators packed 250 times (650 KB, 23 to 29 s), and three
1209
+ pages that each run 40 MB (160 KB, 6 to 14 s at a time);
1210
+ - a Type3 font whose one glyph paints a form 390,000 times, which pdf.js ran when a page set the
1211
+ font (3 KB, 9 s at 730 MB).
1212
+
1213
+ All but the first need `@cantoo/pdf-lib` installed (the page check, under **Upgrading**);
1214
+ without it, the 23 KB file is refused at 16 MB of text, in under 6 s. Two forms that paint each
1215
+ other are read, as pdf.js reads them.
1216
+ - **A large upload no longer holds the server while it is read.** An ingest held the event loop
1217
+ for most of its time, and every answer streaming on that server stopped with it. Measured on one
1218
+ machine (Node 24, Windows), three times each, the longest gap of a 5 ms timer during the ingest
1219
+ of a 99 MB log went from 1.9 to 2.0 s down to 31 to 34 ms, and of a 2,000-page PDF from 4.4 to
1220
+ 4.5 s down to 0.16 s. The log took 1.9 s to ingest either way; the PDF 4.9 to 5.0 s, against 4.6
1221
+ to 4.9 s. A line of megabytes is cleaned in pieces too: one line of 30 MB with a control
1222
+ character between its letters held the event loop for 1.9 s, with 761 MB of memory, and now for
1223
+ 71 to 76 ms, with 250 MB. What is left comes from the cut of a long line into lines of 2,000
1224
+ characters, which still runs in one block: 0.21 to 0.23 s for a line of 66 million characters.
1225
+ - **A look at the pages of a PDF lets other requests run while it parses the file, copies the
1226
+ pages and writes the cut.** In 0.5.0 a look held the event loop for nearly its whole time: one
1227
+ page that refers to 20,000 large arrays held it 1.87 to 2.02 s of 3.8 to 3.9 s, and pages of a
1228
+ 2,000-page PDF 159 to 177 ms of 163 to 185 ms. Now the longest holds are 43 to 47 ms and 19 to
1229
+ 20 ms (Windows, Node 24). A cut is the same to the byte as before (65 cuts of 50 PDFs compared).
1230
+ Each look still reads and parses the whole file, and the first look of a process loads
1231
+ `@cantoo/pdf-lib` in one block (about 0.4 s, unless the server loads it when it starts).
1232
+ - **A PDF name escaped again and again no longer holds the server.** A name such as
1233
+ `/#2323...2341` loses one level each time it is decoded, and both the page check and a look at
1234
+ the pages decoded every name of a page until nothing changed, in one block: time grew with the
1235
+ square of its length. A name is now decoded at most three times, and one that would still
1236
+ change is taken as a name that cannot be read: the page check counts it as naming any drawing,
1237
+ and a look keeps every image of the page. Measured on one machine (Linux, Node 22), the ingest
1238
+ of a 0.4 MB PDF with one such name of 400,000 characters in its resources ran over 90 s and now
1239
+ takes 0.27 s, and a look at its page ran over 90 s and now takes under 0.2 s; a PDF of under 20 KB whose content paints 40 such
1240
+ names of 30,000 characters went from 11.7 s to 0.41 s. Names that real files write are read as
1241
+ before.
1242
+
1243
+ Access:
1244
+
1245
+ - **`files.tools()` checks the owner of each document it reads.** In 0.5.0, a loop of your own
1246
+ that built a `DocumentMeta` from an ID a client sent could read the text of another owner's
1247
+ document through the tools, and show the pages of its PDF (see **Upgrading**).
1248
+ - **Changing metadata that `MemoryDocumentStore` handed out no longer changes the document.**
1249
+ `ingest` and `getMeta` returned the store's own object: deleting `owner` from it before sending
1250
+ it to a browser opened the document to every owner. `FileDocumentStore` was not affected.
1251
+
1252
+ Searches:
1253
+
1254
+ - **A model asked when something last happened can now see the last matching line.** In a live
1255
+ check on Vertex AI, with gemini-3.1-flash-lite and a 3 MB production log, the model counted the
1256
+ 442 PAY-5031 errors right, then named line 12,088 as the last one. It was line 15,269: the
1257
+ search showed the first matches only, and said nothing of the others (see **Upgrading**). A way
1258
+ to page through all the matches is planned for 0.7.0.
1259
+ - **A search that stopped early and was cut to the size limit still says that its total is a
1260
+ lower bound.** 0.5.0 replaced that note with the note of the cut.
1261
+ - **Steps say "1 matching line", "1 passage", "1 part" and "1 more tool call in this turn was not
1262
+ run"**, where 0.5.0 said "1 matching lines" and so on. Likewise, a file of one line is `1 line`
1263
+ in its frame and its card, and a PDF of one page is `1 page` in its card.
1264
+
1265
+ Text files and what the model reads:
1266
+
1267
+ - **A Hebrew CSV that Excel saved in windows-1255 can be searched.** 0.5.0 stored its 30 rows as
1268
+ U+FFFD, and "ירושלים" was found in none of them; now it is found in all 30. Arabic in
1269
+ windows-1256, Russian in windows-1251, French in windows-1252, and Japanese in Shift_JIS are read
1270
+ the same way (see **Upgrading**).
1271
+ - **An export in CESU-8 is read with its emoji.** An Oracle database in its character set `UTF8`,
1272
+ and Java's modified UTF-8, write a character past U+FFFF as two halves of a surrogate pair. When
1273
+ that is the only thing wrong with a file, it is read as UTF-8, with the pairs joined. 0.5.0
1274
+ stored each such emoji as six U+FFFD.
1275
+ - **Tag characters, and the controls that reorder what a person sees, are removed at ingest.** A
1276
+ line with 44 Unicode tag characters, which spell out an instruction that a model reads and a
1277
+ person does not see, sent all 44 to the model, and a file name kept them too. Characters that
1278
+ scripts and emoji need are kept, and a crafted file can still carry data a person does not see
1279
+ in them ([Characters that show nothing](docs/security.md#characters-that-show-nothing)). The
1280
+ library does not detect instructions.
1281
+ - **An exact search finds a word split by a zero-width space or a soft hyphen**, in a file
1282
+ ingested from now on: `pass\u200bword` now matches a search for "password".
1283
+ - **A file's own lines, and its name, no longer pass for the end of its frame.** A file sent whole
1284
+ could hold `--- End attached file: report.txt ---`, the same line the library writes. The frame
1285
+ lines now carry a mark that the file cannot know (see **Upgrading**); it does not make the model
1286
+ obey, and it is not a secret ([The frame around a file](docs/security.md#the-frame-around-a-file)).
1287
+ - **No half of an emoji reaches Claude.** 0.5.0 cut text inside a character outside the basic
1288
+ plane, which JSON writes as `\ud83d` and Claude's API refuses: in tool results, search lines,
1289
+ stand-ins, the first lines of a card, log templates, the problem message of a call whose
1290
+ arguments could not be read, and file names, cut at 255 characters. These are now cut before
1291
+ such a character. What 0.5.0 stored cut that way (log templates, search windows in stored tool
1292
+ rounds, names) is sent with U+FFFD in place of the half, and `getMeta` returns a name the same
1293
+ way; the stored data is not changed. An emoji of several characters, such as a flag, can still
1294
+ lose its end at the cut of a name.
1295
+
1296
+ Ingest:
1297
+
1298
+ - **An outline of 20 to 399 top-level headings keeps each of them once, in order.** In a document
1299
+ of more than 400 headings, such an outline took its entries from the first headings only, some
1300
+ more than once: with 20 top-level headings, the first one 20 times. It was so in 0.5.0 and every
1301
+ version before. Ingest a document again to rebuild its outline.
1302
+
1303
+ The tool loop:
1304
+
1305
+ - **The calls of a turn share the room that is left.** Each call took its whole cap in call
1306
+ order, so the first calls could take all the room, and the next were told "no room left, answer
1307
+ now". The room is now shared evenly, and only calls that cannot each get 1,500 characters are
1308
+ refused.
1309
+ - **Whole-file reads in one turn are counted together** against `limits.requests` and
1310
+ `limits.inputTokens`: two reads that each fit passed the ceiling together (16 requests against
1311
+ 11 in a probe). Their input tokens are counted by the `tokenScale` of the model that reads the
1312
+ parts, and the provider's count of a request by that of the model that gave it, not by the
1313
+ largest scale of the question.
1314
+ - **Part reads of a `generateText` that does not call `onUsage` count toward `limits.requests`**
1315
+ and `usage.requests`. They were left out.
1316
+ - **The request for an answer after no tool ran is `FINAL_ANSWER_WITHOUT_TOOLS`**, also when the
1317
+ first reply was empty or no turn was left for tools. It said "using only what the tools returned
1318
+ above".
1319
+
1320
+ Whole-file reads:
1321
+
1322
+ - **A read whose last step failed returns the notes of its parts**, with `notes_only: true`,
1323
+ instead of an error that lost every part already paid for.
1324
+ - **A model that asks again for a read that could read no part is told that it failed, and why**,
1325
+ not to "use the answer of that read". A read that failed before any model request (a store that
1326
+ could not be read) can be made again.
1327
+ - **A long answer is cut at its end**, with `answer_shortened`, and the other fields
1328
+ (`parts_read`, the notes on what is incomplete) are kept. It was cut as JSON, which dropped them.
1329
+ - **A part that could not be read from storage no longer shows the model the server's file
1330
+ path**, only the error code ("The file could not be read from storage (EACCES). Try the call
1331
+ again.").
1332
+ - **One HTTP 400 no longer turns the larger output limit off for every later question.** A part
1333
+ refused as too large for the window with 32,768 output tokens was taken for a model that refuses
1334
+ that limit: every later part on that model, in that process, was sent with 4,096, and a model
1335
+ that thinks got no text.
1336
+ - **One part refused by the per-minute token limit no longer blocks whole-file reads for the rest
1337
+ of the process.** The larger output limit stayed learned, and every later part asked for it
1338
+ again and was refused. Now an allowance of no more than 32,768 tokens turns it off for the model.
1339
+ With a fake OpenAI-compatible server, 12 of 12 parts were read in 15 requests, where main
1340
+ (5157e7f) read none in 34.
1341
+ - **Claude: a part read that thought most of its output limit away is asked again with the larger
1342
+ limit** (`THINKING_OUTPUT_TOKENS`), as Gemini and OpenAI-compatible part reads are. Its notes
1343
+ came back cut: two lines out of 4,096 tokens.
1344
+
1345
+ The adapters:
1346
+
1347
+ - **All three: a connection that failed while the body of a reply arrived is sent again**, like
1348
+ one that failed before the reply. In 0.5.0 a chat reply that came in one piece was not.
1349
+ - **A stream that closes without saying why it ended is not taken for a whole reply**: Gemini's
1350
+ last chunk has a `finishReason`, an OpenAI-compatible stream a `finish_reason` or `[DONE]`, and
1351
+ a Claude stream a `stop_reason`. A proxy or a dropped connection made a cut answer, or a cut turn
1352
+ of tool calls, count as whole (see **Upgrading**). On Claude, a call whose block was never closed
1353
+ is answered "send it again", not run with no arguments. DeepSeek's
1354
+ `insufficient_system_resource` is the server's failure (HTTP 503), not a whole reply.
1355
+ - **OpenAI-compatible and Claude: a stream that said it is whole returns its reply, though the
1356
+ server then left the connection open, or the connection broke.** After `[DONE]` or
1357
+ `message_stop`, the body is read for at most one more second, and then cancelled. With 0.5.0,
1358
+ such a request waited until the server closed the connection, and failed when it broke.
1359
+ - **A streamed reply through a `fetch` whose body is a Node stream** (node-fetch) failed with
1360
+ "stream.getReader is not a function". Both kinds of body are read.
1361
+ - **A streamed event longer than 64,000,000 characters ends the reply**, with an error of kind
1362
+ `"invalid"` and status 200 that is not sent again:
1363
+ `The model's reply could not be read: an event of its stream held more than 64,000,000 characters.`
1364
+ (Claude's and Gemini's say the same). Such a reply now ends after about 62 MB, in 0.4 s, with
1365
+ 165 MB more memory. 0.5.0 had no cap: it grew one string with the event, and searched all of it
1366
+ again for each piece that came (see the next point). On main (5157e7f), whose parser did the
1367
+ same, an event without an end grew a string until it failed, with 600 to 740 MB more memory, or
1368
+ ran the heap out of memory. A reply made of many events, and a reply that is not streamed, have
1369
+ no cap yet.
1370
+ - **`parseSseJson` reads each piece of a body once.** One event of 8 MB in pieces of 16 KB took
1371
+ 0.97 to 1.19 s with 0.5.0; it now takes 10 to 20 ms (ten runs each, Node 24, Windows). See
1372
+ [Measurements](docs/measurements.md#the-server).
1373
+ - **OpenAI-compatible: an error whose message is at the top of the body is read** (`message`
1374
+ from vLLM before its OpenAI-shaped errors, SGLang and FastChat; `detail` from servers built on
1375
+ FastAPI). A request too large for the model failed with "The model returned HTTP 400."; it now
1376
+ carries the server's message, with kind `"context_overflow"`, and is made smaller (see
1377
+ **Changed**).
1378
+ - **OpenAI-compatible: a streamed reply keeps its `refusal`, and OpenRouter's `reasoning` and
1379
+ `reasoning_details`** (the thought signature of a Gemini 3 model behind OpenRouter).
1380
+ - **OpenAI-compatible: a server that sends the name of a tool call again with each piece** no
1381
+ longer makes it `search_documentsearch_document`, an unknown tool.
1382
+ - **OpenAI-compatible: a call whose arguments are empty or not JSON goes back as `"{}"`.** vLLM
1383
+ before 0.29 refused the next request (HTTP 400).
1384
+ - **OpenAI-compatible: part reads send `max_completion_tokens` to every Azure OpenAI host.** When
1385
+ `maxTokensField` is not set, a server that refuses the name it was sent (HTTP 400 naming it) is
1386
+ sent the other, and the adapter keeps it.
1387
+ - **OpenAI-compatible: two user turns in a row are sent as one.** DeepSeek's reasoner and the chat
1388
+ templates of Mistral and Gemma models refuse them.
1389
+ - **Claude: an empty text block is not sent back** ("text content blocks must be non-empty"),
1390
+ unless a thinking block follows it in the turn.
1391
+ - **Claude: calls of other providers and of earlier questions get IDs the API takes**, each once
1392
+ in a request: Kimi's `functions.search:0` becomes `functions_search_0`.
1393
+
1394
+ Retries:
1395
+
1396
+ - **`retries: NaN` no longer sends a failing request again without end.** A `NaN`, such as
1397
+ `Number(process.env.RETRIES)` with the variable unset, never ran out: a request that kept failing
1398
+ with status 0, 408, 409, 429 or 5xx was sent again until the signal aborted. A `baseDelayMs` or
1399
+ `maxDelayMs` of `NaN` cut the waits to about 1 ms. Each now takes its default.
1400
+
1401
+ Packaging:
1402
+
1403
+ - **npm installs llm-large-files next to unpdf 2** (`^1.4.0 || ^2.0.0`; unpdf 2 asks for Node
1404
+ 24). With 0.5.0, an app that already had unpdf 2 could not install llm-large-files: npm stopped
1405
+ with `ERESOLVE`. The 12 PDFs of the tests give the same text, pages, picture marks and page cuts
1406
+ with every unpdf from 1.4.0 to 2.2.1, and CI runs the tests with unpdf 1.7.0 on Node 20, the
1407
+ newest 1.x on Node 22 and 24, and the newest 2.x on Node 24.
1408
+
1409
+ ## 0.5.0 and earlier
1410
+
1411
+ Versions 0.1.0 to 0.5.0 are recorded in the
1412
+ [full history up to 0.5.0](https://github.com/renanbazinin/llm-large-files/blob/v0.5.0/CHANGELOG.md).
1413
+ Each of them but 0.1.0 is a [tag of the repository](https://github.com/renanbazinin/llm-large-files/tags);
1414
+ from 0.6.0 on, each release is also on the
1415
+ [GitHub releases page](https://github.com/renanbazinin/llm-large-files/releases).