llm-large-files 0.5.0 → 0.8.0

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