llm-large-files 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +1402 -467
  2. package/README.md +188 -60
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +190 -39
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +60 -4
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1068 -206
  14. package/dist/ask.js.map +1 -1
  15. package/dist/encoding.d.ts +17 -0
  16. package/dist/encoding.d.ts.map +1 -0
  17. package/dist/encoding.js +852 -0
  18. package/dist/encoding.js.map +1 -0
  19. package/dist/errors.d.ts +4 -0
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +15 -0
  22. package/dist/errors.js.map +1 -1
  23. package/dist/events.d.ts +333 -0
  24. package/dist/events.d.ts.map +1 -0
  25. package/dist/events.js +159 -0
  26. package/dist/events.js.map +1 -0
  27. package/dist/evidence.d.ts +2 -0
  28. package/dist/evidence.d.ts.map +1 -1
  29. package/dist/evidence.js +3 -2
  30. package/dist/evidence.js.map +1 -1
  31. package/dist/extract.d.ts +35 -3
  32. package/dist/extract.d.ts.map +1 -1
  33. package/dist/extract.js +626 -58
  34. package/dist/extract.js.map +1 -1
  35. package/dist/gemini/adapter.d.ts +17 -8
  36. package/dist/gemini/adapter.d.ts.map +1 -1
  37. package/dist/gemini/adapter.js +108 -61
  38. package/dist/gemini/adapter.js.map +1 -1
  39. package/dist/gemini/chat.d.ts +23 -3
  40. package/dist/gemini/chat.d.ts.map +1 -1
  41. package/dist/gemini/chat.js +6 -2
  42. package/dist/gemini/chat.js.map +1 -1
  43. package/dist/gemini/errors.d.ts +9 -4
  44. package/dist/gemini/errors.d.ts.map +1 -1
  45. package/dist/gemini/errors.js +32 -0
  46. package/dist/gemini/errors.js.map +1 -1
  47. package/dist/gemini/generate.d.ts +10 -2
  48. package/dist/gemini/generate.d.ts.map +1 -1
  49. package/dist/gemini/generate.js +13 -7
  50. package/dist/gemini/generate.js.map +1 -1
  51. package/dist/gemini/index.d.ts +3 -3
  52. package/dist/gemini/index.d.ts.map +1 -1
  53. package/dist/gemini/index.js +2 -2
  54. package/dist/gemini/index.js.map +1 -1
  55. package/dist/gemini/sse.d.ts +1 -1
  56. package/dist/gemini/sse.d.ts.map +1 -1
  57. package/dist/gemini/sse.js +1 -1
  58. package/dist/gemini/sse.js.map +1 -1
  59. package/dist/http.d.ts +116 -0
  60. package/dist/http.d.ts.map +1 -1
  61. package/dist/http.js +347 -1
  62. package/dist/http.js.map +1 -1
  63. package/dist/index.d.ts +11 -6
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +6 -4
  66. package/dist/index.js.map +1 -1
  67. package/dist/library.d.ts +67 -5
  68. package/dist/library.d.ts.map +1 -1
  69. package/dist/library.js +405 -85
  70. package/dist/library.js.map +1 -1
  71. package/dist/map-reduce.d.ts +28 -1
  72. package/dist/map-reduce.d.ts.map +1 -1
  73. package/dist/map-reduce.js +240 -52
  74. package/dist/map-reduce.js.map +1 -1
  75. package/dist/model.d.ts +84 -2
  76. package/dist/model.d.ts.map +1 -1
  77. package/dist/model.js +182 -1
  78. package/dist/model.js.map +1 -1
  79. package/dist/node/handlers.d.ts +20 -4
  80. package/dist/node/handlers.d.ts.map +1 -1
  81. package/dist/node/handlers.js +122 -20
  82. package/dist/node/handlers.js.map +1 -1
  83. package/dist/node/index.d.ts +2 -0
  84. package/dist/node/index.d.ts.map +1 -1
  85. package/dist/node/index.js +1 -0
  86. package/dist/node/index.js.map +1 -1
  87. package/dist/node/sse.d.ts +59 -0
  88. package/dist/node/sse.d.ts.map +1 -0
  89. package/dist/node/sse.js +174 -0
  90. package/dist/node/sse.js.map +1 -0
  91. package/dist/openai/adapter.d.ts +29 -5
  92. package/dist/openai/adapter.d.ts.map +1 -1
  93. package/dist/openai/adapter.js +311 -37
  94. package/dist/openai/adapter.js.map +1 -1
  95. package/dist/output-limit.d.ts +14 -2
  96. package/dist/output-limit.d.ts.map +1 -1
  97. package/dist/output-limit.js +39 -10
  98. package/dist/output-limit.js.map +1 -1
  99. package/dist/pause.d.ts +24 -0
  100. package/dist/pause.d.ts.map +1 -0
  101. package/dist/pause.js +38 -0
  102. package/dist/pause.js.map +1 -0
  103. package/dist/pdf-pages.d.ts +32 -2
  104. package/dist/pdf-pages.d.ts.map +1 -1
  105. package/dist/pdf-pages.js +275 -14
  106. package/dist/pdf-pages.js.map +1 -1
  107. package/dist/pdf-pictures.d.ts +30 -3
  108. package/dist/pdf-pictures.d.ts.map +1 -1
  109. package/dist/pdf-pictures.js +50 -8
  110. package/dist/pdf-pictures.js.map +1 -1
  111. package/dist/pdf-work.d.ts +40 -0
  112. package/dist/pdf-work.d.ts.map +1 -0
  113. package/dist/pdf-work.js +734 -0
  114. package/dist/pdf-work.js.map +1 -0
  115. package/dist/plan.d.ts +22 -4
  116. package/dist/plan.d.ts.map +1 -1
  117. package/dist/plan.js +61 -12
  118. package/dist/plan.js.map +1 -1
  119. package/dist/retry.d.ts +23 -1
  120. package/dist/retry.d.ts.map +1 -1
  121. package/dist/retry.js +33 -3
  122. package/dist/retry.js.map +1 -1
  123. package/dist/search.d.ts +8 -2
  124. package/dist/search.d.ts.map +1 -1
  125. package/dist/search.js +60 -10
  126. package/dist/search.js.map +1 -1
  127. package/dist/sse.d.ts +35 -2
  128. package/dist/sse.d.ts.map +1 -1
  129. package/dist/sse.js +145 -31
  130. package/dist/sse.js.map +1 -1
  131. package/dist/stores.d.ts.map +1 -1
  132. package/dist/stores.js +5 -2
  133. package/dist/stores.js.map +1 -1
  134. package/dist/text-index.d.ts +6 -0
  135. package/dist/text-index.d.ts.map +1 -1
  136. package/dist/text-index.js +25 -8
  137. package/dist/text-index.js.map +1 -1
  138. package/dist/text.d.ts +62 -2
  139. package/dist/text.d.ts.map +1 -1
  140. package/dist/text.js +314 -14
  141. package/dist/text.js.map +1 -1
  142. package/dist/tools.d.ts +61 -1
  143. package/dist/tools.d.ts.map +1 -1
  144. package/dist/tools.js +269 -42
  145. package/dist/tools.js.map +1 -1
  146. package/dist/types.d.ts +102 -3
  147. package/dist/types.d.ts.map +1 -1
  148. package/dist/zip-directory.d.ts +43 -0
  149. package/dist/zip-directory.d.ts.map +1 -0
  150. package/dist/zip-directory.js +130 -0
  151. package/dist/zip-directory.js.map +1 -0
  152. package/docs/README.md +288 -0
  153. package/docs/api.md +37 -381
  154. package/docs/configuration.md +28 -558
  155. package/docs/getting-started.md +407 -223
  156. package/docs/guides/anthropic.md +590 -0
  157. package/docs/guides/conversations.md +629 -0
  158. package/docs/guides/costs-and-limits.md +726 -0
  159. package/docs/guides/deployment.md +654 -0
  160. package/docs/guides/errors-and-reliability.md +735 -0
  161. package/docs/guides/explorer-model.md +399 -0
  162. package/docs/guides/openai-compatible.md +602 -0
  163. package/docs/guides/own-adapter-and-loop.md +1169 -0
  164. package/docs/guides/pdfs.md +971 -0
  165. package/docs/guides/storage.md +731 -0
  166. package/docs/guides/testing.md +1199 -0
  167. package/docs/guides/vertex-and-gemini.md +717 -0
  168. package/docs/guides/web-app.md +1589 -0
  169. package/docs/how-it-works.md +1012 -164
  170. package/docs/measurements.md +881 -0
  171. package/docs/publishing.md +274 -46
  172. package/docs/reference/anthropic.md +427 -0
  173. package/docs/reference/ask.md +892 -0
  174. package/docs/reference/errors-and-retries.md +758 -0
  175. package/docs/reference/events.md +993 -0
  176. package/docs/reference/gemini.md +823 -0
  177. package/docs/reference/library.md +1467 -0
  178. package/docs/reference/node.md +528 -0
  179. package/docs/reference/openai.md +385 -0
  180. package/docs/reference/tools.md +883 -0
  181. package/docs/security.md +897 -103
  182. package/docs/troubleshooting.md +1390 -0
  183. package/package.json +2 -2
  184. package/src/analyze.ts +93 -42
  185. package/src/anthropic/adapter.ts +196 -39
  186. package/src/ask.ts +1087 -202
  187. package/src/encoding.ts +850 -0
  188. package/src/errors.ts +17 -0
  189. package/src/events.ts +442 -0
  190. package/src/evidence.ts +5 -2
  191. package/src/extract.ts +602 -62
  192. package/src/gemini/adapter.ts +118 -65
  193. package/src/gemini/chat.ts +28 -4
  194. package/src/gemini/errors.ts +34 -1
  195. package/src/gemini/generate.ts +23 -10
  196. package/src/gemini/index.ts +3 -3
  197. package/src/gemini/sse.ts +1 -1
  198. package/src/http.ts +376 -1
  199. package/src/index.ts +27 -5
  200. package/src/library.ts +459 -85
  201. package/src/map-reduce.ts +252 -51
  202. package/src/model.ts +236 -3
  203. package/src/node/handlers.ts +137 -22
  204. package/src/node/index.ts +2 -0
  205. package/src/node/sse.ts +198 -0
  206. package/src/openai/adapter.ts +306 -38
  207. package/src/output-limit.ts +44 -8
  208. package/src/pause.ts +41 -0
  209. package/src/pdf-pages.ts +268 -15
  210. package/src/pdf-pictures.ts +56 -9
  211. package/src/pdf-work.ts +722 -0
  212. package/src/plan.ts +68 -12
  213. package/src/retry.ts +49 -5
  214. package/src/search.ts +63 -10
  215. package/src/sse.ts +153 -28
  216. package/src/stores.ts +5 -2
  217. package/src/text-index.ts +26 -7
  218. package/src/text.ts +323 -13
  219. package/src/tools.ts +261 -42
  220. package/src/types.ts +107 -4
  221. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,654 @@
1
+ # Deployment
2
+
3
+ This page is for running an application built on llm-large-files in production: on several
4
+ servers, behind a proxy or a load balancer, through restarts and upgrades. It says what state lives
5
+ where, what the shared store must guarantee, how much memory a server needs, how to sweep expired
6
+ documents, how to keep a streamed answer alive, and what Node.js and packages a production image
7
+ needs.
8
+
9
+ ## What lives where
10
+
11
+ A question is one call (`askWithFiles` or `askGemini`) that runs on one server from the plan to
12
+ the answer. Everything it needs comes from the store and from the conversation your application
13
+ passes in. What a server keeps in memory between two questions is a cache, which it can always
14
+ rebuild from the store.
15
+
16
+ | State | Where it lives | Shared by your servers | After a restart |
17
+ |---|---|---|---|
18
+ | Documents: metadata, text, line index, kept originals | The `DocumentStore` | Must be | Kept (lost with `MemoryDocumentStore`) |
19
+ | Conversations: messages and `toolTurns` | Your application's storage | Yours to share | Yours |
20
+ | Which documents belong to which user or chat | Your application, and `owner` on each document | Yours to share | Yours |
21
+ | Documents ready to search, decoded pieces of large ones, line indexes | A cache in each `LargeFiles`, within `cacheBytes` | No | Empty; filled again from the store |
22
+ | Searches of large files waiting their turn | A queue in each `LargeFiles` (`maxConcurrentScans`) | No | Empty |
23
+ | The output limit a thinking model needs for whole-file part reads | Each process, by URL and model | No | Learned again, at the cost of one request |
24
+ | The name of the output limit an OpenAI-compatible server takes | Each `openAiCompatible()` adapter | No | Learned again, at the cost of one refused request |
25
+
26
+ What follows from it:
27
+
28
+ - **Any server can answer any question**, when the store is shared and your application sends the
29
+ whole conversation, `toolTurns` included ([Conversations](./conversations.md)). No sticky
30
+ sessions are needed.
31
+ - **A server never serves a document that is gone.** Every use of a cached document asks the store
32
+ first (`getMeta`), so a document deleted on one server, or expired, is gone on all of them at
33
+ once. A cached copy is used only while the store still describes the same text (its `createdAt`,
34
+ `textBytes`, `characters` and `lines`).
35
+ - **Create `files` once per process**, at startup, and import it everywhere. Each
36
+ `createLargeFiles` call has its own cache and its own queue of scans: one per request would read
37
+ every document from the store again and multiply the memory limits. Create adapters once too, so
38
+ that what they learn is kept.
39
+ - **Nothing coordinates your servers.** `limits` apply to one question, each server retries its own
40
+ requests, and the provider's quota is shared by all of them
41
+ ([Errors and reliability](./errors-and-reliability.md), [Costs and limits](./costs-and-limits.md)).
42
+
43
+ ## A shared store
44
+
45
+ Several servers need one store that all of them read. Whatever it is built on, it must guarantee
46
+ this:
47
+
48
+ - **A write is seen by every server once it has returned.** The browser uploads to one server and
49
+ asks on another a second later. A store whose reads lag its writes makes the new document look
50
+ missing, and the question throws `DocumentsNotFoundError`.
51
+ - **A delete is seen by every server once it has returned.** The cache of each server relies on
52
+ `getMeta` to know that a document is gone.
53
+ - **A document appears whole.** `ingest` writes the original and the line index first, and calls
54
+ `put` last; `put` must make the metadata visible only after the text. A server that finds the
55
+ metadata must be able to read the text.
56
+ - **The text is kept byte for byte.** `readTextRange` reads UTF-8 byte offsets that the line index
57
+ computed at ingest. A text that changed is noticed ("The stored text of … did not match its
58
+ index. Try the call again.") and its index is built again.
59
+ - **`undefined` means "not there", and nothing else.** A read that failed (a timeout, a volume that
60
+ does not answer) must throw: the library passes it on as `DocumentStoreError` instead of telling
61
+ the user that the file is gone.
62
+ - **Two servers can do the same thing at once.** Two sweeps or two deletes of one document must
63
+ not fail, and two servers saving the index of an older document at the same time must leave one
64
+ whole index (the last write wins).
65
+ - **`getMeta` is fast.** It is called for each document at the start of every question, and again
66
+ for every tool call that reads a document.
67
+
68
+ The built-in stores:
69
+
70
+ - **`MemoryDocumentStore`** lives in one process. With several servers, each sees only its own
71
+ uploads: use it for tests and one-process demos only.
72
+ - **`FileDocumentStore`** works on a volume that every server mounts. It writes each file under a
73
+ temporary name and renames it, so no server reads half a file; it writes the metadata last and
74
+ deletes it first; it throws every error reading the metadata, the text or the original other
75
+ than "no such file" (an index it cannot read is built again from the text); and its `sweep` leaves
76
+ alone the files of an upload that may still be in progress (see
77
+ [Sweeping expired documents](#sweeping-expired-documents)).
78
+
79
+ It needs a file system whose rename is atomic and that shows each server the files of the
80
+ others: an NFS share (Amazon EFS, Google Filestore, Azure Files over NFS) or similar. Two caveats:
81
+
82
+ - An NFS client may remember for a while that a file did not exist (its negative lookup cache).
83
+ A question sent to another server right after an upload can then find the document missing.
84
+ Mount the share with `lookupcache=positive` (or `none`).
85
+ - A bucket mounted as a file system (gcsfuse, s3fs and the like) often does not rename
86
+ atomically. Write a store over the bucket's own API instead.
87
+
88
+ - **A store of your own**, over MongoDB, S3, Cloud Storage, Redis or a database: see
89
+ [Storage](./storage.md) for the contract method by method and a complete example.
90
+
91
+ ## Memory on each server
92
+
93
+ | What takes memory | How much | What bounds it |
94
+ |---|---|---|
95
+ | Documents kept ready to search | Up to `cacheBytes`, 256 MB by default | `cacheBytes`; `cacheSize` also caps their number |
96
+ | A document loaded whole: text up to `wholeDocumentBytes` (2 MB), or any size when the store has no `readTextRange` | Its text and a lowercased copy: 2 bytes a character for ASCII text, 4 for any other | Counted in `cacheBytes`. One larger than `cacheBytes` is loaded again for each call and not kept |
97
+ | A document read by range | Its line index: about 8 bytes a line (8.2 MB for a log of a million lines) | Counted in `cacheBytes` |
98
+ | Searches of documents read by range | A few MB each: `scanChunkBytes` (1 MB) of text read, decoded and lowercased, and the next piece read ahead | `maxConcurrentScans` (4) per `LargeFiles`. The others wait, and those waiting for the same file share one pass over it |
99
+ | Decoded pieces of a document read by range | Up to its whole decoded text | Kept within `cacheBytes`, and only for a document whose decoded text takes at most a quarter of it |
100
+ | An upload | The body, buffered whole | `maxUploadBytes`, 100 MB by default |
101
+ | An ingest | Several copies of the text at once (below), and what the parsers of PDF, DOCX and PPTX take while they read. A crafted PDF can make them take far more: one of 732 bytes ran a heap of 512 MB out of memory, and one of 1.6 KB took 1.6 GB of memory outside the heap, with 20 MB of heap, for a stream that unpacks to 512 MB ([Security](../security.md#uploads)) | `maxTextBytes` bounds the text (100 MB by default). Nothing bounds what the PDF parsers build or unpack. One at a time, or in a process of its own with a memory limit of its own (below) |
102
+ | A look at the pages of a PDF (`view_pages`) | The whole original, read and parsed: about twice the size of the file, plus 1 to 1.6 KB for each object in it (about 300 MB for a 100 MB file of photos, 700 MB for 54 MB of 330,000 objects). A crafted file can take far more: a look at a PDF of 8 MB that is one array of numbers took 422 to 427 MB of heap, one of 16 MB ran a heap of 512 MB out of memory, and one at the PDF of 1.6 KB above took 1.1 GB outside the heap. What `@cantoo/pdf-lib` keeps after a look adds up from file to file, until the server restarts | Refused for a file that declares more than 1,000,000 objects, or more objects than about 60% of the free heap can hold. A crafted file of few objects passes that check. Ingested in a process of its own (below), with `@cantoo/pdf-lib` installed, a file that needs more than that process's heap fails there and is not stored; one that fits is parsed again by each look, which takes more than its ingest did (232 to 244 MB for that file of 8 MB). For the documents of users you do not trust, `viewPages: false`, or no PDF originals |
103
+ | A question in flight | Its conversation, and each request it builds: up to `maxRequestBytes` (10 MB by default) of JSON, the pages it was shown included as base64 | The budget ([Costs and limits](./costs-and-limits.md)) |
104
+
105
+ Measured peaks are in [Measurements](../measurements.md#the-server): an ingest of a plain-text log
106
+ takes about five to seven times the log above the uploaded bytes, and eight searches at once take
107
+ little more than one.
108
+
109
+ Other formats were not measured for memory. PDF text is extracted by pdf.js, which reads the whole
110
+ file, and with `@cantoo/pdf-lib` installed the file is parsed a second time, before pdf.js reads a
111
+ page, for the page check and to mark the pages that show a picture (not for a file that declares
112
+ more than 150,000 objects; the marks are also given up when finding the pictures takes more than
113
+ 5 seconds once the file is parsed). A PDF of more than `maxPdfPages`
114
+ (5,000) pages, and a file of more than `maxTextBytes` of text, are refused
115
+ ([Security](../security.md#uploads)). The peak memory of `view_pages` on real files is in
116
+ [measurements](../measurements.md).
117
+
118
+ Set the heap limit of Node yourself: about three quarters of the memory of the container when
119
+ everything runs in one process, less when ingest runs in a process of its own. The limit is more
120
+ than the flag. `--max-old-space-size` sets the old generation, and Node adds its young generation
121
+ above it: 48 MB on Node 20 and 22, 192 MB on Node 24, and 96 MB on Node 26.
122
+ `v8.getHeapStatistics().heap_size_limit` gives the sum. For three quarters of 2 GB, a limit of
123
+ 1,536 MB:
124
+
125
+ | Node | Flag for a heap limit of 1,536 MB | What `--max-old-space-size=1536` gives |
126
+ |---|---|---|
127
+ | 20 and 22 | `NODE_OPTIONS=--max-old-space-size=1488` | 1,584 MB |
128
+ | 24 | `NODE_OPTIONS=--max-old-space-size=1344` | 1,728 MB, 84% of 2 GB |
129
+ | 26 | `NODE_OPTIONS=--max-old-space-size=1440` | 1,632 MB |
130
+
131
+ Checked with `heap_size_limit` on Node 20.19, 22.12, 24.19 and 26.13. Upload bodies and files read
132
+ from the store are `Buffer`s, which live outside the heap and need the rest. The check that refuses
133
+ a PDF too large to cut pages from compares it with the free heap, so a heap set to fit the
134
+ container makes that check right.
135
+
136
+ A worker thread does not get a heap limit of its own when the process has one: a
137
+ `--max-old-space-size` on the command line or in `NODE_OPTIONS` replaces the
138
+ `resourceLimits.maxOldGenerationSizeMb` of every worker. With `--max-old-space-size=1024`, a worker
139
+ given 512 MB had the process's limit: 1,072 MB on Node 20 and 22, 1,216 MB on Node 24, 1,120 MB on
140
+ Node 26. Setting `execArgv: []` or `env` on the worker did not change it. A forked process does get
141
+ its own: one forked with `execArgv: ["--max-old-space-size=512"]` had 560 MB on Node 20 and 22,
142
+ 704 MB on Node 24 and 608 MB on Node 26, with `NODE_OPTIONS=--max-old-space-size=1024` in the
143
+ environment it inherits or without it.
144
+
145
+ A starting point for a container of 2 GB, to check under your own load. The heaps are heap limits,
146
+ not flags:
147
+
148
+ | Node | Main heap of 1 GB | Ingest heap of 512 MB |
149
+ |---|---|---|
150
+ | 20 and 22 | `--max-old-space-size=976` | `--max-old-space-size=464` |
151
+ | 24 | `--max-old-space-size=832` | `--max-old-space-size=320` |
152
+ | 26 | `--max-old-space-size=928` | `--max-old-space-size=416` |
153
+
154
+ The flags 1024 and 512 give heap limits of 1,216 and 704 MB on Node 24: 1,920 MB, which leaves
155
+ about 128 MB of the container for the upload, its copy, files read from the store and two Node
156
+ processes. On Node 20 and 22 they give 1,072 and 560 MB.
157
+
158
+ ```ts
159
+ // large-files.ts: created once per process and imported by every route.
160
+ // Run with a heap of 1 GB: NODE_OPTIONS=--max-old-space-size=832 on Node 24 (the table above has
161
+ // the others). Ingests run in a process of their own (below).
162
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
163
+
164
+ export const files = createLargeFiles({
165
+ store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents"),
166
+ keepOriginals: ["pdf"], // view_pages: a look reads the whole PDF into this heap
167
+ cacheBytes: 256 * 1024 * 1024, // the default
168
+ maxConcurrentScans: 4, // the default
169
+ maxUploadBytes: 100 * 1024 * 1024, // the default
170
+ });
171
+ ```
172
+
173
+ | Where 2 GB go | |
174
+ |---|---|
175
+ | The main heap, 1 GB | The cache (256 MB), the questions in flight, a look at the pages of a PDF |
176
+ | One ingest at a time, in a process with a heap of 512 MB | An ingest of a 95 MB log fitted in a heap of 256 MB. A process takes about 50 MB more for Node itself |
177
+ | Outside the heaps | The upload being read (up to 100 MB) and its copy sent to the ingest process, files read from the store, Node itself. Also what the PDF parsers unpack, which no heap limit bounds: a crafted PDF of 1.6 KB took 1.6 GB at ingest and 1.1 GB at a look, far more than this row has left. For uploads you do not trust, give the ingest process a container of its own, and do not offer `view_pages` on their documents |
178
+
179
+ Raise `cacheBytes` to spend memory on speed: at 1 GB, the decoded pieces of an ASCII log of up to
180
+ about 125 MB are kept between searches. Lower `maxUploadBytes` if large uploads are not needed:
181
+ an ingest is one of the largest single uses of memory.
182
+
183
+ ### Uploads and ingest
184
+
185
+ `createDocumentHandlers` reads the whole upload into memory before it calls `ingest`. It refuses a
186
+ body whose `Content-Length` is over `maxUploadBytes` before reading it, and stops reading one that
187
+ grows past it (HTTP 413). Node's own `server.requestTimeout` (300,000 ms by default) ends an upload
188
+ that takes longer than five minutes to arrive: raise it for users on slow links.
189
+
190
+ An ingest runs in your server's process, a slice at a time. It pauses for other requests about
191
+ every 12 ms of its work, so an answer streaming on the same server waits a fraction of a second,
192
+ not seconds: the longest stall measured was 34 ms for a 99 MB log and 0.16 s for a 2,000-page
193
+ PDF, where 0.5.0 held the server for 2.0 s and 4.5 s ([measured](../measurements.md#the-server)).
194
+ A text file in an older encoding is decoded a megabyte at a time, and a line of megabytes is
195
+ cleaned in pieces of 256K characters: one line of 30 MB with a control character between its
196
+ letters held the server for 71 to 76 ms, where 0.5.0 held it about 1.9 s. One page of a PDF still
197
+ holds the server for as long as pdf.js takes to read it. With
198
+ `@cantoo/pdf-lib` installed, a page that would take long is refused before pdf.js reads any page
199
+ (a page built to paint forms inside forms held the server for 13 s to 2 minutes without that
200
+ check); a page that passes can still take about 1.5 s, more in a large file
201
+ ([Pages that would hold the server](./pdfs.md#pages-that-would-hold-the-server)). It has limits too: `maxTextBytes` (the text kept from
202
+ one file, 100 MB by default), `maxPdfPages` (5,000) and `ingestTimeoutMs` (2 minutes) refuse a file
203
+ that would cost more ([Security](../security.md#uploads)).
204
+
205
+ The first PDF a process reads also loads the PDF parsers, in one block that no pause can split:
206
+ about 0.4 s for `@cantoo/pdf-lib` and 0.05 s for pdf.js, measured on Node 24. Since 0.6.0 it loads
207
+ `@cantoo/pdf-lib` even with `pictures: false`, for the page check. An app that reads PDFs with
208
+ `createPdfExtractor({ pictures: false, checkPages: false })` does not load it at ingest, but then no
209
+ page is checked ([PDFs](./pdfs.md#pages-that-would-hold-the-server)). Load them when the server
210
+ starts, before it takes requests:
211
+
212
+ ```ts
213
+ // Before the server listens: the first upload of a PDF then does not hold it while they load.
214
+ await import("@cantoo/pdf-lib");
215
+ await (await import("unpdf")).getResolvedPDFJS();
216
+ ```
217
+
218
+ `getResolvedPDFJS()` rejects when the `unpdf` installed cannot load pdf.js on this Node (unpdf 1.9
219
+ and later on Node 20), and the server then does not start: install the version for your Node
220
+ ([PDFs and other formats](./pdfs.md#formats)).
221
+
222
+ What it does not do is keep its memory apart. The text and its copies, and what pdf.js,
223
+ `@cantoo/pdf-lib` and JSZip take while they read, are in your server's heap, with the cache and the
224
+ questions in flight. A file that needs more than the heap has left stops the whole process, and
225
+ every answer streaming on it. A step under way, such as one slow page of a PDF, also runs to its
226
+ end after the time limit. Three ways to bound that:
227
+
228
+ - **Accept one or two ingests at a time** per server, and answer the others with 503 (the sample
229
+ below does it): this bounds memory and keeps stalls from adding up.
230
+ - **Ingest in a process of its own**, with a heap limit and a time limit: below. A process that
231
+ runs out of memory stops alone, and the upload is answered with an error. The heap limit does not
232
+ bound what a parser unpacks outside the heap: a crafted PDF of 1.6 KB took 1.6 GB that way
233
+ ([Security](../security.md#uploads)). For uploads you do not trust, give that process a memory
234
+ limit of its own too, such as a container or a cgroup of its own, or use a service of its own.
235
+ - **Ingest in a service of its own.** All the state is in the store, so an upload service with its
236
+ own `createLargeFiles` and `createDocumentHandlers`, on servers sized for uploads, can write the
237
+ documents that the chat servers read. Give it the options that apply at ingest, the same as the
238
+ chat servers would have: `ttlMs`, `maxUploadBytes`, `maxTextBytes`, `maxPdfPages`,
239
+ `ingestTimeoutMs`, `extractors`, `keepOriginals` and `scannedPdfPages`. The chat servers need the
240
+ options that apply to reading: `cacheBytes`, `cacheSize`, `wholeDocumentBytes`, `scanChunkBytes`,
241
+ `maxConcurrentScans` and `budget`.
242
+
243
+ **Not a worker thread.** For uploads you do not trust, the security page of 0.5.0 suggested a
244
+ worker thread or a separate process, and a draft of this guide on GitHub, before 0.6.0, ran each
245
+ ingest in a worker thread
246
+ (`ingestInWorker`) with `resourceLimits: { maxOldGenerationSizeMb: 512 }`. That keeps the event
247
+ loop free, but it does not bound memory. The process's heap flag replaces the worker's limit (see
248
+ [Memory on each server](#memory-on-each-server)): under `NODE_OPTIONS=--max-old-space-size=1024`,
249
+ as that draft set it, that worker had 1,216 MB on Node 24, not 512. And a worker that runs out of
250
+ memory can take the whole process down with it: in the 0.6 review, on the code before this release
251
+ ([Measurements](../measurements.md#how-to-read-this-page)), a worker of 512 MB, with no heap flag
252
+ on the process, did so on a hostile DOCX. A child process stops alone.
253
+
254
+ A process that runs one ingest, with the options of `large-files.ts` above:
255
+
256
+ ```ts
257
+ // ingest-process.ts: one ingest, in a process of its own, forked by documents.ts below.
258
+ import type { IngestInput } from "llm-large-files";
259
+ import { files } from "./large-files.js"; // the same options as the chat routes
260
+
261
+ process.once("message", async (message) => {
262
+ try {
263
+ process.send!({ meta: await files.ingest(message as IngestInput) });
264
+ } catch (error) {
265
+ const { code, syscall, status, statusCode } = (error ?? {}) as { code?: unknown; syscall?: unknown; status?: unknown; statusCode?: unknown };
266
+ const httpStatus = typeof status === "number" ? status : typeof statusCode === "number" ? statusCode : undefined;
267
+ process.send!({
268
+ failed: error instanceof Error ? {
269
+ message: error.message,
270
+ // What createDocumentHandlers answers by: a status (a 503 from your store or an OCR service),
271
+ // or the code and syscall of a failure of the store (500). Without either, a 422 with this
272
+ // message, even for an error of your store (below).
273
+ ...(httpStatus !== undefined ? { status: httpStatus } : {}),
274
+ ...(typeof code === "string" && typeof syscall === "string" ? { code, syscall } : {}),
275
+ } : {
276
+ // Not an Error: its code and syscall when it has both, or else a 500 with no message.
277
+ // createDocumentHandlers answers it as it does without this process: with the code, or with
278
+ // { "error": "Upload failed." }.
279
+ message: "",
280
+ ...(typeof code === "string" && typeof syscall === "string" ? { code, syscall } : { status: 500 }),
281
+ },
282
+ });
283
+ }
284
+ });
285
+ ```
286
+
287
+ The upload routes, with `ingest` replaced by one that forks that process. `createDocumentHandlers`
288
+ takes any `LargeFiles`, so the rest stays as it is:
289
+
290
+ ```ts
291
+ // documents.ts: the upload routes. Each ingest runs in a process of its own, one at a time on this server.
292
+ import { fork } from "node:child_process";
293
+ import type { DocumentMeta, IngestInput } from "llm-large-files";
294
+ import { createDocumentHandlers } from "llm-large-files/node";
295
+ import { files } from "./large-files.js";
296
+ import { userIdOf } from "./auth.js"; // your sign-in
297
+
298
+ const INGESTS_AT_ONCE = 1;
299
+ let running = 0;
300
+
301
+ type IngestReply = { meta?: DocumentMeta; failed?: { message: string; code?: string; syscall?: string; status?: number } };
302
+
303
+ function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
304
+ if (input.signal?.aborted) return Promise.reject(input.signal.reason);
305
+ if (running >= INGESTS_AT_ONCE) {
306
+ // An error with a status is answered with that status and its message.
307
+ return Promise.reject(Object.assign(new Error("The server is reading other files. Try again in a minute."), { status: 503 }));
308
+ }
309
+ running++;
310
+ return new Promise<DocumentMeta>((resolve, reject) => {
311
+ const child = fork(new URL("./ingest-process.js", import.meta.url), {
312
+ // A heap of its own: a limit of 512 MB on Node 24, whose young generation adds 192 MB to the
313
+ // flag (the table above has the flags of other versions). This flag wins over a
314
+ // --max-old-space-size in NODE_OPTIONS, which the child inherits.
315
+ execArgv: ["--max-old-space-size=320"],
316
+ serialization: "advanced", // the bytes go as they are, not as JSON
317
+ });
318
+ let reply: IngestReply | undefined;
319
+ let timedOut = false;
320
+ let settled = false;
321
+ // Above ingestTimeoutMs (120 s by default), so that the library's own message comes first. This
322
+ // ends a step that cannot be stopped, such as one slow page of a PDF.
323
+ const timer = setTimeout(() => {
324
+ timedOut = true;
325
+ child.kill();
326
+ }, 150_000);
327
+ // The upload handler aborts the signal when the client goes away: nobody waits for this file.
328
+ const stop = () => child.kill();
329
+ input.signal?.addEventListener("abort", stop, { once: true });
330
+ // The slot is free once the process is gone, and only then is the upload answered: a user who
331
+ // sends the next file as soon as this one is answered does not find the slot still taken.
332
+ const settle = () => {
333
+ if (settled) return;
334
+ settled = true;
335
+ clearTimeout(timer);
336
+ input.signal?.removeEventListener("abort", stop);
337
+ running--;
338
+ if (reply?.meta) resolve(reply.meta);
339
+ else if (input.signal?.aborted) reject(input.signal.reason);
340
+ // With a status, that status and message (a 503 from your store or an OCR service); with a
341
+ // code and a syscall, a failure of the store (500); otherwise a file that cannot be read
342
+ // (422), even when the error came from your store (below).
343
+ else if (reply?.failed) reject(Object.assign(new Error(reply.failed.message), reply.failed));
344
+ else if (timedOut) reject(new Error(`${input.name} took too long to read.`));
345
+ // Out of memory, or crashed: that process is gone, and this server goes on.
346
+ else reject(new Error(`${input.name} could not be read on this server.`));
347
+ };
348
+ child.once("message", (message) => {
349
+ reply = message as IngestReply;
350
+ child.kill(); // its work is done: the file is stored, or refused
351
+ });
352
+ child.once("exit", settle);
353
+ child.once("error", () => {
354
+ child.kill();
355
+ settle();
356
+ });
357
+ // The bytes are copied to the process. A signal cannot be sent: the process has its own
358
+ // ingestTimeoutMs, and is killed when this one aborts.
359
+ const { signal: _signal, ...message } = input;
360
+ child.send(message);
361
+ });
362
+ }
363
+
364
+ export const documents = createDocumentHandlers({ ...files, ingest: ingestInProcess }, { getOwner: userIdOf });
365
+ ```
366
+
367
+ Checked on Node 24: with `NODE_OPTIONS=--max-old-space-size=1024` on the server and a heap of 48 MB
368
+ for the child, a 2,000-page PDF ran the child out of memory; the upload was answered "book.pdf
369
+ could not be read on this server.", and the next upload was ingested.
370
+
371
+ The error that `ingestInProcess` rebuilds from the process's reply is a new `Error`, so
372
+ `createDocumentHandlers` cannot tell a store that failed to write from a file that cannot be read.
373
+ Given `files` itself, it answers a store's error that has no status, and no `code` and `syscall`,
374
+ with 500 `{ "error": "Upload failed." }`. Through this process, it answers that error 422 with the
375
+ store's own message, which may name a database host. Give your store's errors a status and a
376
+ message of your own, as [Storage](./storage.md#errors) shows: the process passes the status on. A
377
+ thrown value that is not an `Error` gets the same answer with the process as without it.
378
+
379
+ A process stopped by its limit or its timeout may leave the files of a document that was never
380
+ finished. `FileDocumentStore` removes them at the first sweep after they are an hour old. One
381
+ stopped after its document was stored leaves a whole document whose ID nobody got: it expires
382
+ like any other.
383
+
384
+ ### Pages of PDFs
385
+
386
+ `view_pages` runs on the chat server, not where the file was ingested. Each look reads the whole
387
+ original from the store, parses it with `@cantoo/pdf-lib`, copies the pages and writes the cut. It
388
+ cannot be stopped once it has started, and it pauses after every 12 ms of work so that other
389
+ requests get a turn (after up to 40 ms where a timer is slow, as on Windows). One object of the
390
+ file is parsed in one block: about 0.1 to 0.35 s for each MB, by what it holds, so a crafted PDF of
391
+ 16 MB that is one array of numbers held the server 1.7 to 3.5 s on each look, on a heap that could
392
+ hold it. Its memory and its limits are in the table above. The check that refuses a file too large
393
+ compares it with the free heap, so set the heap limit (above). That check counts the objects a file
394
+ declares, not what they take: a crafted file that a process of its own ingested can still run the
395
+ chat server out of memory at its first look, or take memory outside the heap. And what
396
+ `@cantoo/pdf-lib` keeps after each look adds up from file to file: files of 9 KB ran a heap of 1 GB
397
+ out of memory at the seventh look ([Security](../security.md#reading-pdfs-for-pages-and-pictures)).
398
+ For the documents of users you do not trust, do not offer `view_pages` (`viewPages: false`), or keep
399
+ no PDF originals. To offer it anyway, run each of their questions, the whole tool loop, in a process
400
+ you fork, with its own heap and memory limits. What the model is told when pages cannot be shown,
401
+ and the rest of `view_pages`, are in [PDFs and other formats](./pdfs.md); without `keepOriginals`
402
+ nothing is kept and nothing is cut.
403
+
404
+ ## Sweeping expired documents
405
+
406
+ A document expires `ttlMs` after its upload (72 hours by default; `Infinity` never). The library
407
+ checks `expiresAt` on every use, so an expired document is never served, whether or not it was
408
+ swept. `files.sweep()` only frees the space: it calls the store's `sweep` and returns how many
409
+ documents it removed, or 0 for a store without one.
410
+
411
+ `FileDocumentStore.sweep` also removes the files of uploads that were never finished, once they are
412
+ `orphanAgeMs` old (one hour by default): younger ones may be an upload in progress on another
413
+ server ([Storage](./storage.md#filedocumentstore)).
414
+
415
+ **Where to run it.** On one server, or from a scheduled job. Running it on every server is safe
416
+ with `FileDocumentStore`, since removing a file that another sweep just removed is no error, but
417
+ each server then lists the whole directory and reads every metadata file. A job of its own:
418
+
419
+ ```ts
420
+ // sweep.ts: run every hour by a scheduled job (cron, a Kubernetes CronJob, Cloud Scheduler).
421
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
422
+
423
+ const files = createLargeFiles({ store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents") });
424
+ const removed = await files.sweep();
425
+ console.log(`Removed ${removed} expired documents.`);
426
+ ```
427
+
428
+ **How often.** Once an hour is a good start. A document then takes space for up to `ttlMs` plus one
429
+ interval. On disk, `FileDocumentStore` keeps for each document its text, its metadata, its line
430
+ index (about 8 bytes a line) and, with `keepOriginals`, the uploaded file: a 95 MB log, without
431
+ its original, takes about 103 MB until it is swept.
432
+
433
+ A store that expires records itself (a MongoDB TTL index on a date copy of `expiresAt`, which the
434
+ metadata holds as a string; a lifecycle rule on a bucket) needs no sweep for them: see
435
+ [Storage](./storage.md).
436
+
437
+ ## Streamed answers behind proxies
438
+
439
+ A streamed answer is a long HTTP response that is silent for long stretches. Before the first word
440
+ of the answer:
441
+
442
+ - a model that thinks sends nothing until it has thought;
443
+ - an explorer's requests are not streamed by `gemini()` and `openAiCompatible()`, so each one
444
+ arrives whole at the end ([An explorer model](./explorer-model.md));
445
+ - a search of a large file, or a whole-file read of many requests, takes seconds to minutes;
446
+ - a request that failed is sent again after a wait of up to 60 seconds (`retry.maxDelayMs`).
447
+
448
+ `onStep` and `onActivity` report the steps between requests, but nothing comes during a chat
449
+ request: one stretch can last up to `firstByteTimeoutMs`, 10 minutes by default. Once the answer streams,
450
+ two pieces can be up to `idleTimeoutMs` apart, 5 minutes by default. The adapters' waits are in
451
+ [Errors and reliability](./errors-and-reliability.md).
452
+
453
+ ### Keep the stream alive
454
+
455
+ Many proxies and load balancers close a connection on which nothing came for a while: nginx after
456
+ `proxy_read_timeout` (60 seconds by default), an AWS Application Load Balancer after its idle
457
+ timeout (60 seconds by default). Send a comment line every 15 seconds. A line that starts with `:`
458
+ is a comment in Server-Sent Events: browsers skip it, and the proxy sees traffic.
459
+
460
+ The route in [Web app](./web-app.md) does it: it sends the stream with
461
+ `Cache-Control: no-cache, no-transform` and `X-Accel-Buffering: no`, and writes a `: keep-alive`
462
+ comment every 15 seconds. That page also has the events themselves and a reader over `fetch`.
463
+ `EventSource` ignores comments; a reader of your own must skip a block that has no `data:` line.
464
+
465
+ ### Turn off buffering
466
+
467
+ A proxy that buffers the response holds the events back and lets them through in bunches, or only
468
+ at the end. nginx buffers by default (`proxy_buffering on`): an `X-Accel-Buffering: no` header on
469
+ the response turns it off for that response. Compression middleware buffers too: the Express
470
+ `compression` package skips a response marked `Cache-Control: no-transform`, or sends what it has
471
+ when you call `res.flush()` after each event. Check any CDN in front of your server for the same.
472
+
473
+ ### Limits on the whole response
474
+
475
+ Some platforms and load balancers limit the time of the whole response, not the silence, and a
476
+ heartbeat does not reset that. Cloud Run's request timeout is 5 minutes by default (60 at most),
477
+ and the backend service timeout of Google Cloud's Application Load Balancers is 30 seconds by
478
+ default. Check what yours counts, and set it above your deadline for a question.
479
+
480
+ ### The order of the timeouts
481
+
482
+ | Timeout | Set it to | Why |
483
+ |---|---|---|
484
+ | Your heartbeat | 15 seconds | Below every idle timeout on the way to the browser |
485
+ | Idle timeouts of proxies and load balancers | Anything above the heartbeat | The heartbeat keeps the connection busy |
486
+ | `firstByteTimeoutMs`, `idleTimeoutMs` of the adapter | The defaults (600 s, 300 s), or lower for a model that does not think long | A silent request is aborted and sent once more |
487
+ | Your deadline for a question (`signal`) | What your users will wait, for example 15 minutes. When it is below `firstByteTimeoutMs` (600 s by default), lower `firstByteTimeoutMs` too, or a silent request is ended by the deadline before it can be sent again | The question has none of its own. Yours ends it with your message, and `partialResultOf` keeps what it found |
488
+ | Limits on the whole response | Above your deadline | Otherwise the proxy cuts the stream first, and the user gets no message |
489
+ | A gateway between your server and the model | Above the time the slowest request takes to its first byte | A gateway that gives up answers 504, which is sent again and fails again |
490
+
491
+ How to build the deadline and tell it apart from a user who left is in
492
+ [Errors and reliability](./errors-and-reliability.md). Gateways in front of the model are covered
493
+ in [Gemini API and Vertex AI](./vertex-and-gemini.md) and
494
+ [OpenAI-compatible endpoints](./openai-compatible.md).
495
+
496
+ When the stream is cut anyway (a proxy, a dropped connection), there is no resume: your server sees
497
+ the response close, the question's `signal` should abort it so that it stops costing, and the user
498
+ asks again.
499
+
500
+ ## Restarts and rolling upgrades
501
+
502
+ ### Stopping a server
503
+
504
+ A question under way when its server stops is lost: the stream to the browser ends, and nothing
505
+ picks the question up. Let the questions under way finish within your platform's grace period, and
506
+ stop the rest yourself so that they end with a message and keep what they found:
507
+
508
+ ```ts
509
+ // shutdown.ts
510
+ import type { Server } from "node:http";
511
+
512
+ /** Aborted when this server is told to stop. Each question passes it in its signal. */
513
+ export const stopping = new AbortController();
514
+
515
+ /** Call once the server listens. `graceMs`: a little less than your platform's grace period. */
516
+ export function stopOnSigterm(server: Server, graceMs = 25_000): void {
517
+ process.once("SIGTERM", () => {
518
+ server.close(); // no new connections; requests under way go on
519
+ // Before the grace period runs out, stop the questions still running.
520
+ setTimeout(() => stopping.abort(new Error("The server is restarting.")), graceMs).unref();
521
+ });
522
+ }
523
+
524
+ // In the chat route:
525
+ // signal: AbortSignal.any([userLeft.signal, stopping.signal, AbortSignal.timeout(15 * 60_000)])
526
+ // and when it throws with stopping.signal.aborted: tell the user to ask again, and store
527
+ // partialResultOf(error)?.toolTurns with the conversation.
528
+ ```
529
+
530
+ Abort with an `Error`, as here, not a string: `partialResultOf` needs an object to look the
531
+ question up by. An upload cut by the restart leaves files that the sweep removes an hour later.
532
+
533
+ After a restart the cache is empty: the first tool calls read their documents from the store again,
534
+ and a thinking model's first whole-file read in the new process may spend one request finding the
535
+ output limit it needs.
536
+
537
+ ### Servers of two versions
538
+
539
+ During a rolling upgrade, servers of the old and the new version share the store and answer the
540
+ same conversations.
541
+
542
+ - **Documents.** The files of `FileDocumentStore` have not changed since 0.4.0: `<id>.json`,
543
+ `<id>.txt`, `<id>.idx` and `<id>.bin`, with the same index format. Servers of 0.4.x, 0.5.x and
544
+ 0.6.x share one directory, and each reads the documents the others wrote. Run the sweep from a
545
+ server of the newest version: since 0.4.1 it leaves alone a document whose metadata it could not
546
+ read. A document ingested before 0.4.1 has no `jsonBytes`: planning then assumes its text takes
547
+ 8% more in JSON. One ingested before 0.4.0 has no index: it is built the first time the document
548
+ is used, and saved for the other servers. Upgrading from 0.3.x has notes of its own in
549
+ [the 0.4.0 entry of the changelog](https://github.com/renanbazinin/llm-large-files/blob/v0.5.0/CHANGELOG.md#040---2026-11-12).
550
+ - **A document keeps what the version that ingested it extracted**: its text, outline and log
551
+ profile. A better extractor applies to files uploaded after the upgrade. A text file in an older
552
+ encoding that 0.5.0 stored holds U+FFFD where 0.6.0 reads its letters, and text that 0.5.0
553
+ stored keeps the characters that show nothing and Word's hidden text unmarked: upload such a file
554
+ again to get the new reading. A document that 0.5.0 stored with the owner `""` stays readable
555
+ with that owner until it expires.
556
+ - **Conversations.** `toolTurns` are plain JSON, and their type (`ToolTurn`) has not changed since
557
+ they appeared in 0.5.0. Both versions read the ones the other stored. 0.6.0 sends the rounds of
558
+ an earlier question without their `tool_turns_left`
559
+ ([Conversations](./conversations.md#what-toolturns-holds)).
560
+ - **Provider caches.** The tool guide in the system instruction, the descriptions of
561
+ `analyze_whole_document` and `search_document`, and the frame lines of a file sent whole changed
562
+ in 0.6.0. They come at the start of a request, so a request
563
+ sent with the new text cannot reuse what the provider cached of the old: in each conversation
564
+ whose files are searched or sent whole, the first request after the upgrade pays the full input
565
+ price once for what comes from the first text that changed on
566
+ ([Costs and limits](./costs-and-limits.md#prompt-caching)), with Claude's `cache_control` as a
567
+ cache write.
568
+ While servers of both versions answer the same conversation in turn, it can miss more often:
569
+ finish the rollout quickly, or keep a conversation on one version while it runs if that cost
570
+ matters. Any upgrade that changes this text has the same effect; the
571
+ [changelog](../../CHANGELOG.md) says when one does.
572
+
573
+ ## Node.js, ESM and `require()`
574
+
575
+ - **Node.js 20.19 or newer** (`engines` in `package.json`). The tests run on Node 20, 22 and 24,
576
+ and again with unpdf 1.7.0 on Node 20, the newest 1.x on Node 22 and 24, and the newest 2.x on
577
+ Node 24. Pick the `unpdf` for your Node ([PDFs and other formats](./pdfs.md#formats)).
578
+ - **The package is ESM only.** It has `"type": "module"` and an `exports` map with `types` and
579
+ `default`; there is no CommonJS build. An ESM application imports it as it is.
580
+ - **A CommonJS application can `require()` it** on Node 20.19 and newer in the 20 line, and on Node
581
+ 22.12 and newer: those load an ES module with `require()`, and the library has no top-level
582
+ `await`. On Node 22.0 to 22.11, load it with `import()` from an async function: a CommonJS file
583
+ has no top-level `await`, so write `const { createLargeFiles } = await import("llm-large-files");`
584
+ inside `async function main() { ... }`.
585
+
586
+ ```js
587
+ // CommonJS, Node 20.19+ or 22.12+
588
+ const { createLargeFiles, FileDocumentStore } = require("llm-large-files");
589
+ const { askGemini, vertexAi } = require("llm-large-files/gemini");
590
+ const { createDocumentHandlers } = require("llm-large-files/node");
591
+ ```
592
+
593
+ - **TypeScript that compiles to CommonJS**: use `"module": "nodenext"`, which lets a CommonJS file
594
+ import an ES module. With `"node16"` or `"node18"`, TypeScript refuses the import (TS1479).
595
+ `"module": "commonjs"` with `"moduleResolution": "node10"` also works, and finds the types of the
596
+ subpaths through `typesVersions`. Checked with TypeScript 5.9, and the output run on Node 24.
597
+
598
+ ```json
599
+ {
600
+ "compilerOptions": {
601
+ "module": "nodenext",
602
+ "moduleResolution": "nodenext"
603
+ }
604
+ }
605
+ ```
606
+
607
+ - **Bundlers.** The optional packages below are loaded with a dynamic `import()` when they are
608
+ first needed. A bundle of your server must keep them resolvable at run time: mark them external,
609
+ and install them next to the bundle.
610
+
611
+ ## Optional dependencies in production images
612
+
613
+ Three formats and features need packages that npm does not install with this one: they are
614
+ optional peer dependencies. Add the ones you need to the `dependencies` of your application, not
615
+ `devDependencies`, which `npm ci --omit=dev` leaves out of a production image.
616
+
617
+ | Package | Version | Needed for | Without it |
618
+ |---|---|---|---|
619
+ | `unpdf` | `^1.4.0 \|\| ^2.0.0`, in a version that runs on your Node: 1.7.0 on Node 20, a 1.x from 1.6.1 on Node 22, any on Node 24 and later ([PDFs](./pdfs.md#formats)) | The text of PDFs | The upload is refused: `Reading PDF files needs the optional dependency "unpdf".` (422 from `createDocumentHandlers`). A version that does not run on your Node is refused too, with a message that says what to install: `The unpdf installed cannot read PDF files on Node 20 (…). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.` |
620
+ | `jszip` | `^3.10.0` | DOCX and PPTX | The upload is refused: `Reading DOCX and PPTX files needs the optional dependency "jszip".` |
621
+ | `@cantoo/pdf-lib` | `^2.11.1` | `view_pages`, the check of PDF pages that would hold the server, and the marks on PDF pages that show a picture | `view_pages` answers the model `report.pdf: Showing PDF pages needs the optional dependency "@cantoo/pdf-lib".` (with the file's name), and PDFs are ingested without the check and without the marks, with no error |
622
+
623
+ The last one fails quietly at ingest, so an image without it ingests PDFs differently from your
624
+ machine, and lets through the pages the check would refuse. On Node 24 and later,
625
+ `npm install unpdf` installs unpdf 2, which does not run on Node 20: for an image on Node 20 or 22,
626
+ name the version in your `dependencies`. Check at startup that the image has what your application
627
+ uses:
628
+
629
+ ```ts
630
+ // check-dependencies.ts: run at startup, before the server listens.
631
+ const needed = ["unpdf", "jszip", "@cantoo/pdf-lib"]; // the ones your application uses
632
+ for (const name of needed) {
633
+ try {
634
+ await import(name);
635
+ } catch {
636
+ throw new Error(`${name} is not installed: add it to the dependencies of this application.`);
637
+ }
638
+ }
639
+ ```
640
+
641
+ What each format gives, and the rules for an extractor of your own, are in
642
+ [PDFs and other formats](./pdfs.md).
643
+
644
+ ## Related pages
645
+
646
+ - [Storage](./storage.md): the `DocumentStore` contract, a store of your own, owners and retention.
647
+ - [Web app](./web-app.md): uploads, the events of a streamed answer, cancelling.
648
+ - [Errors and reliability](./errors-and-reliability.md): the waits of the adapters, retries, a
649
+ deadline for a question.
650
+ - [Conversations](./conversations.md): what to store so that any server can answer the next question.
651
+ - [Security](../security.md): uploads you do not trust, the cost of a question.
652
+ - Reference: [`LargeFilesOptions`](../reference/library.md#largefilesoptions),
653
+ [`FileDocumentStore`](../reference/library.md#filedocumentstore),
654
+ [`createDocumentHandlers`](../reference/node.md#createdocumenthandlersfiles-options).