llm-large-files 0.8.2 → 0.10.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 (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
@@ -0,0 +1,890 @@
1
+ # Upgrading to 0.9
2
+
3
+ This page takes an application from 0.8.x (0.8.0 to 0.8.2) to 0.9.0. Most applications change no
4
+ code: read [Requirements](#requirements), [Does my code compile?](#does-my-code-compile) and
5
+ [Behavior to check](#behavior-to-check). The other sections are for a store of your own, several
6
+ servers on one store, and an application that keeps files on a shared volume per user and chat.
7
+ Every change is in the [changelog](../CHANGELOG.md).
8
+
9
+ 0.9.0 lets one library serve every user and chat of a server process. Each store call carries the
10
+ scope and the owner of the call. `FileDocumentStore` can keep a folder per user and chat. A
11
+ document can take your application's ID. The uploads your application keeps are read where they
12
+ are, instead of copied into the store. The text sent to the model is the same as in 0.8.2 for
13
+ ordinary chats, so the provider's prompt cache is not lost at the upgrade
14
+ ([What did not change](#what-did-not-change)).
15
+
16
+ ## Contents
17
+
18
+ - [Requirements](#requirements)
19
+ - [Does my code compile?](#does-my-code-compile)
20
+ - [Behavior to check](#behavior-to-check)
21
+ - [Stores of your own](#stores-of-your-own)
22
+ - [Several servers and rolling deploys](#several-servers-and-rolling-deploys)
23
+ - [A worked example: a Hebrew chatbot on Gemini, MongoDB and a shared volume](#a-worked-example-a-hebrew-chatbot-on-gemini-mongodb-and-a-shared-volume)
24
+ - [Moving the documents of 0.8](#moving-the-documents-of-08)
25
+ - [What did not change](#what-did-not-change)
26
+ - [New and optional](#new-and-optional)
27
+
28
+ ## Requirements
29
+
30
+ - **Node.js 22.12 or later.** `engines.node` is `>=22.12`; it was `>=20.19`. Node 22.0 to 22.11
31
+ cannot `require()` the package from CommonJS. CI runs Node 22, 24 and 26, on Ubuntu and Windows,
32
+ and 22.12.0 on Ubuntu, where it also checks `require()` of every subpath of the packed tarball.
33
+ npm only warns (`EBADENGINE`) unless `engine-strict` is set, so an app on Node 20 still installs,
34
+ but nothing is tested there.
35
+ - **TypeScript:** `@types/node` 22 or later. The package is checked without the DOM library, as a
36
+ server app compiles, and its declarations need nothing else.
37
+ - **The optional dependencies are unchanged:** `unpdf` `^1.4.0 || ^2.0.0`, `jszip` `^3.10.0`,
38
+ `@cantoo/pdf-lib` `^2.11.1`.
39
+
40
+ ## Does my code compile?
41
+
42
+ Most code does. Every new option and field is optional. Every method of `DocumentStore` takes a new
43
+ last argument, `context`, and it is optional too: a store whose methods take only the arguments of
44
+ 0.8 still implements the interface. These do not compile:
45
+
46
+ | Code of yours | The error | What to write |
47
+ |---|---|---|
48
+ | A `switch` over `NoticeCode` with a `never` check, or a `Record<NoticeCode, …>` | Three new members: `"documents_missing"`, `"document_gone"`, `"page_looks_busy"` | Add them; a `switch` can end in a `default` instead |
49
+ | A `switch` over `IngestErrorCode` with a `never` check, or a `Record<IngestErrorCode, …>` | A new member: `"exists"` (409) | Add it |
50
+ | `event.error.code` used as an `IngestErrorCode`, or a `switch` over it with a `never` check | `EventError.code` is now `IngestErrorCode \| DocumentScopeErrorCode` | Check the code first; a `switch` needs `"exists"` and the three scope codes |
51
+ | Code that reads `input.bytes` of the argument of `ingest` (TS18048, TS2532): a `LargeFiles` of your own whose `ingest` parameter is inferred, the calls of a spy or mock of `files.ingest`, a value typed `Parameters<LargeFiles["ingest"]>[0]`. Or that passes it to a function that takes `IngestInput` (TS2345) | `ingest` takes `IngestInput \| IngestFromSource`: a file can come as a path, without bytes | Narrow `input` |
52
+ | A store of your own, or a subclass of `FileDocumentStore` or `MemoryDocumentStore`, whose method takes a parameter of its own after those of 0.8: `get(id, options?)`, `sweep(now?, dryRun?)` (TS2322, TS2416) | The new `context` takes that place, and the library passes it there | Put your parameter after `context`: `get(id, context?, options?)` |
53
+ | A subclass of `DocumentStoreError` that declares its own `status`, or of `DocumentsNotFoundError` that declares its own `status` or `code` | They are `503`, and `404` and `"documents_missing"` | Leave them out |
54
+ | A subclass of `IngestError`, `DocumentStoreError`, `DocumentsNotFoundError` or `ModelRequestError` with a static `is` that does not fit `(value: unknown) => value is …`, such as one that returns `boolean` (TS2417) | Each of them has a static `is` now | Return `value is` your class, or rename yours |
55
+ | `fromGeminiContents` passed as a callback: `histories.map(fromGeminiContents)` (TS2345) | Its new second parameter would get the index | `histories.map((contents) => fromGeminiContents(contents))` |
56
+ | Code that reads the `messages` of an `AskGeminiOptions` back, or types a history as `AskGeminiOptions["messages"]`, and reads `text` of a turn (TS2339), or passes it where `Array<ChatTurn \| ToolTurn>` is expected (TS2345) | `messages` is `ChatMessage[]`, as `askWithFiles` takes it: a turn may have `parts` instead of `text` | Type the history `Array<ChatTurn \| ToolTurn>`, or check `"text" in turn` |
57
+
58
+ The fixes, for a page that words notices and the errors of uploads, and for a wrapper of the
59
+ library:
60
+
61
+ ```ts
62
+ import type { EventError, IngestErrorCode, LargeFiles, NoticeCode } from "llm-large-files";
63
+
64
+ /** The words of a notice for your page, or none. */
65
+ export function noticeLabel(code: NoticeCode): string | undefined {
66
+ switch (code) {
67
+ case "documents_missing":
68
+ return "Some files of this chat are no longer available.";
69
+ case "page_looks_busy":
70
+ return "The pages could not be looked at right now.";
71
+ default:
72
+ return undefined; // every other code: "document_gone", those of 0.8, and those a later version adds
73
+ }
74
+ }
75
+
76
+ const uploadWords: Record<IngestErrorCode, string> = {
77
+ empty: "The file is empty.",
78
+ too_large: "The file is too large.",
79
+ too_much_text: "The file has too much text.",
80
+ too_many_pages: "The file has too many pages.",
81
+ not_text: "This kind of file cannot be read.",
82
+ compressed: "The file is compressed.",
83
+ legacy_office: "The Office file is old or has a password.",
84
+ encrypted: "The PDF has a password.",
85
+ no_text: "No text was found in the file.",
86
+ hostile: "The file cannot be read safely.",
87
+ timeout: "The file took too long to read.",
88
+ out_of_memory: "The file needs too much memory to read.",
89
+ busy: "The server is busy. Try again in a moment.",
90
+ missing_dependency: "This kind of file cannot be read on this server.",
91
+ unreadable: "The file could not be read.",
92
+ exists: "This file is already attached.", // new in 0.9.0
93
+ };
94
+ const isIngestCode = (code: string | undefined): code is IngestErrorCode => code !== undefined && Object.hasOwn(uploadWords, code);
95
+ /** The words for the error of an ingest.error event. */
96
+ export const wordsOf = (error: EventError): string => (isIngestCode(error.code) ? uploadWords[error.code] : error.message);
97
+
98
+ /** A wrapper that logs each upload: it narrows the input, which may be a path since 0.9.0. */
99
+ export function loggedFiles(inner: LargeFiles): LargeFiles {
100
+ return {
101
+ ...inner,
102
+ ingest: (input) => {
103
+ console.info(`ingest ${input.name}: ${input.bytes ? `${input.bytes.byteLength} bytes` : "from a path"}`);
104
+ return inner.ingest(input);
105
+ },
106
+ };
107
+ }
108
+ ```
109
+
110
+ - **Narrow, or annotate.** `"source" in input` narrows too. `ingest: (input: IngestInput) => …`
111
+ also compiles, because a method's parameter is compared both ways. But such a wrapper gets a path
112
+ all the same from `createDocumentHandlers` with `uploadSpool` or `prepareUpload`, and its
113
+ `input.bytes` is then undefined. Annotate only a wrapper that is never given a path.
114
+ - **A `LargeFiles` of your own given to `createDocumentHandlers`** must also throw `IngestError`
115
+ for a file it refuses ([below](#the-upload-handler-answers-422-only-for-an-ingesterror)).
116
+
117
+ ## Behavior to check
118
+
119
+ Each point says what changed, whom it affects, and what to do.
120
+
121
+ ### Store failures are `DocumentStoreError`
122
+
123
+ - A store that fails while `files.ingest` writes now throws a `DocumentStoreError` with
124
+ `operation: "write"`, `status: 503`, and the store's own error as `cause`. A write that does not
125
+ end within `ingestTimeoutMs` is one of code `"ETIMEDOUT"`. Before, the store's error came out as
126
+ it was.
127
+ - A failed `files.delete` throws one with `operation: "delete"`, and a failed `files.sweep` one
128
+ with `operation: "sweep"`. They used to pass on the store's errors, which could hold the path of
129
+ the volume.
130
+ - Its message names what failed and a code, never a path or a host: "The document could not be
131
+ stored (EIO). Try again."
132
+ - `DocumentStoreError` has `status: 503`, and `DocumentsNotFoundError` has `status: 404` and
133
+ `code: "documents_missing"`. Their `run.error` events carry these statuses too.
134
+
135
+ **What to do.** Code that caught its own store error class reads `error.cause`. Log `error.cause`:
136
+ the handlers log nothing. Code that takes any error with a numeric `status` for a model's error
137
+ checks these first, with `DocumentStoreError.is(error)` and `DocumentsNotFoundError.is(error)`, or
138
+ reads [`errorInfoOf(error)`](./guides/errors-and-reliability.md#your-users-words-errorinfoof).
139
+
140
+ ### The upload handler answers 422 only for an `IngestError`
141
+
142
+ `createDocumentHandlers` answers errors by the rule of `uploadAnswerOf`
143
+ ([node reference](./reference/node.md#how-errors-are-answered)). What changed (S12):
144
+
145
+ | The error | 0.8.2 | 0.9.0 |
146
+ |---|---|---|
147
+ | A plain `Error` from a `LargeFiles` of your own (no `status`, no system `code`) | 422 with its message, which could name a database host | 500 `{ "error": "Upload failed." }` |
148
+ | An `IngestError` of code `"unreadable"` | 422 with the parser's or extractor's message | 422 "This file could not be read. It may be damaged, or not of the type its name says." |
149
+ | A store that fails while it writes | 500 | 503 with `Retry-After: 5` |
150
+ | A store that fails on `get` or `remove` | 500, such as "The file could not be looked up (EIO)." | 503 with `Retry-After: 5` |
151
+ | A `DocumentScopeError` | 422 with its message | 404 "This chat no longer exists." for `"scope_missing"`, 500 for the other codes |
152
+ | A model's error thrown by an ingest of yours | The provider's status and message | The status and words of `errorInfoOf` |
153
+ | A 413 that the handler did not make (one thrown by `getOwner`, say) | The upload-limit message | Its own message |
154
+
155
+ The handler no longer URI-decodes `Content-Type`; `X-File-Type` still is decoded.
156
+
157
+ **What to do.** Throw `new IngestError(code, message)` for a file you refuse: only an
158
+ `IngestError` keeps its message. The `ingestInProcess` recipe of
159
+ [Deployment](./guides/deployment.md#uploads-and-ingest) rebuilds `IngestError` and
160
+ `DocumentStoreError` from its child process. A route of your own answers as the handler does with
161
+ `uploadAnswerOf`. A client sends a type that needs encoding in `X-File-Type`.
162
+
163
+ ### `requireOwner` and `requireScope` in the handlers
164
+
165
+ Both are new options of `createLargeFiles`, off by default. When the library has them,
166
+ `createDocumentHandlers` throws a `TypeError` without `getOwner`, or without `getScope`. Under
167
+ `requireOwner`, an owner of `undefined` or `null` is a 401 `{ "error": "Sign in first." }` on every
168
+ route, before the body is read, and `""` a 500 "(empty owner)". Documents stored without an owner,
169
+ or without a scope, then read as missing: documents of 0.8, and those that 0.5.0 stored with the
170
+ owner `""`.
171
+
172
+ **What to do.** Give `getOwner` and `getScope`. Turn them on once every server runs 0.9.0, and
173
+ once the documents without an owner or a scope are moved or gone
174
+ ([Moving the documents of 0.8](#moving-the-documents-of-08)).
175
+
176
+ ### `FileDocumentStore` writes files `0600`
177
+
178
+ Files are written `0600` and folders made `0700`. Before, they were `0666` and `0777` minus the
179
+ umask: `0664` and `0775` under the usual `0002`. A server, a sidecar, or a backup or sweep job that
180
+ runs as another user of the same group (a Kubernetes `fsGroup`) reads "The document store could not
181
+ be read (EACCES)".
182
+
183
+ **What to do.** For those, set `fileMode: 0o640` and `directoryMode: 0o750` on every store. Files
184
+ written before keep their modes: `chmod` them once to narrow them.
185
+
186
+ ### `FileDocumentStore` follows no link at a file name
187
+
188
+ On Linux and macOS, the store no longer follows a link at a document's file name. A document whose
189
+ `.json` or `.txt` file is a link, left by a migration or a deduplication, reads as missing. A kept
190
+ copy (`.bin`) that is a link reads as not kept. Windows cannot refuse such a link, so there it is
191
+ followed.
192
+
193
+ **What to do.** Replace such links with the files they point to before you upgrade.
194
+
195
+ ### `files.delete` and leftovers
196
+
197
+ `FileDocumentStore.delete`, and so `files.delete`, returns true once the metadata is gone. A text,
198
+ index or original it cannot remove is left for `sweep`; it used to throw. Removals are tried again
199
+ for about 2.6 s on `EPERM`, `EACCES` and `EBUSY`, as renames are.
200
+
201
+ **What to do.** For erasure, keep a sweep running, or remove the chat's folder. Tests that mock
202
+ `fs.rm` to make a removal fail must mock `unlink`.
203
+
204
+ ### MIME types are cleaned
205
+
206
+ `meta.mimeType` is now a lowercased type/subtype, without parameters: `"Text/CSV; charset=x"` is
207
+ stored as `"text/csv"`. A value that is not a valid type/subtype of at most 127 characters, or that
208
+ holds anything but printable ASCII (a line break, U+202E), is stored as
209
+ `application/octet-stream`. The library never used the charset: it reads a text's encoding from
210
+ its bytes.
211
+
212
+ **What to do.** Compare `meta.mimeType` with the clean form.
213
+
214
+ ### New fields in what you store
215
+
216
+ - `ingest` writes `metaVersion: 1` and `sha256` into every `DocumentMeta`, and `scope` and
217
+ `original` when it is given them.
218
+ - Every `ToolTurn` that `askWithFiles` returns has `version: 1`.
219
+
220
+ **What to do.** Tests that compare a meta or a round whole expect these fields. A schema that
221
+ refuses fields it does not know must allow them: for the metadata a store of yours keeps, and for
222
+ the rounds you keep with each question. Otherwise every ingest fails with a 503
223
+ ([Stores of your own](#allow-the-new-fields)).
224
+
225
+ ### Data written by a newer version
226
+
227
+ - Metadata with `metaVersion` above 1 makes `getMeta`, `getOriginal`, `delete`, `prepare`,
228
+ `askWithFiles` and the tools throw a `DocumentStoreError` of code `"NEWER_VERSION"`. It is not
229
+ read as missing, so your app does not ingest the file again over newer data.
230
+ - A stored `ToolTurn` with `version` above 1 makes `askWithFiles` throw a `TypeError`, before any
231
+ request.
232
+
233
+ **What to do.** Nothing now: only a later version writes such data. While servers of two versions
234
+ share a store, let such a call be tried again on a newer server. Catch the `TypeError` to ask
235
+ again without the old rounds.
236
+
237
+ ### Looks at pages take turns
238
+
239
+ One look at the pages of a PDF (`view_pages`) runs at a time in a library
240
+ (`maxConcurrentPageLooks: 1`), over all its questions. The others wait up to 30 s
241
+ (`pageLookWaitMs`). Past that, the model is told the server is busy, and the question gets a
242
+ `"page_looks_busy"` notice. Six looks at once used to run together, each about four times slower,
243
+ and held 352 MB more than one.
244
+
245
+ **What to do.** Nothing. On a server with heap to spare, raise `maxConcurrentPageLooks`;
246
+ `Infinity` runs every look at once, as in 0.8.2 ([PDFs](./guides/pdfs.md#view_pages)).
247
+
248
+ ### Gemini `contents`
249
+
250
+ `fromGeminiContents`, which `askGemini` uses for `contents`, now turns the library's tool rounds
251
+ back into stored rounds (`ToolTurn`). A repeated call is then answered with a pointer, and old
252
+ results can be shortened, as with `toolTurns`. The first request is the same, byte for byte, for
253
+ rounds that `geminiToolTurns` wrote. Rounds that 0.5.0 converted hold `tool_turns_left` in their
254
+ responses: they are now sent without it, so such a conversation misses the prompt cache once.
255
+
256
+ **What to do.** Nothing. `fromGeminiContents(contents, { rounds: false })` gives the output of 0.8.
257
+ With `askGemini`, pass it as `messages`, which takes what `askWithFiles` takes since 0.9.0:
258
+ `askGemini({ files, endpoint, documentIds, messages: fromGeminiContents(contents, { rounds: false }) })`.
259
+
260
+ ### Tests of the tool loop
261
+
262
+ - A question whose stored rounds make its first request too large is shortened before that
263
+ request. A test sees a `"results_shortened"` step and one request fewer, where it saw a refused
264
+ request and `"room_made"`.
265
+ - A result that its stand-in would not make smaller stays whole: a short grouped search, a small
266
+ `aggregate_table` result.
267
+ - An error of an adapter of yours with a `status` and no `kind`, as `httpError` of
268
+ `llm-large-files/testing` makes, gets a `kind` in its `EventError`: `"server"` for a 503. The
269
+ retries go by that kind: a 429 of code `"insufficient_quota"` is a quota, and is not sent again.
270
+ - The loop goes by that kind too. An `httpError(413)`, a 429 "Request too large … tokens per min",
271
+ or a 400 of code `context_length_exceeded` is a `"context_overflow"` it mends: older results are
272
+ shortened and the request is sent again (`"room_made"`), or a first request is planned again for a
273
+ smaller window (`"replanned"`). A test that expected such a question to fail at once sees one more
274
+ request, and an answer.
275
+ - Thrown plain data with a status (`{ status: 429, message }`) is "Something went wrong." in its
276
+ event.
277
+
278
+ **What to do.** Update tests that compare these whole.
279
+
280
+ ### An ingest stopped during its write keeps nothing
281
+
282
+ When an ingest's `signal` aborts while the store writes, what the writes stored is removed once
283
+ they end, and `ingest` throws `signal.reason`. Before, the document stayed: for good under
284
+ `ttlMs: Infinity`. With the upload handlers, a client that leaves before its ingest ends leaves
285
+ nothing stored, and `onUploaded` is not called.
286
+
287
+ **What to do.** Nothing, unless your code counted on the document of an ingest it stopped.
288
+
289
+ ### `isDocumentId` accepts application IDs
290
+
291
+ It now tests `APP_DOCUMENT_ID_PATTERN`, which the library's own `doc_` IDs match too.
292
+
293
+ **What to do.** To tell the library's IDs from yours, test `DOCUMENT_ID_PATTERN`.
294
+
295
+ ## Stores of your own
296
+
297
+ ### Pass the context on
298
+
299
+ The library now passes `{ scope, owner }` to every store call, as a last argument. A store of 0.8
300
+ ignores it, and still works. A wrapper or a subclass that passes only the ID on still compiles,
301
+ but drops the context:
302
+
303
+ - over a store that keeps the scopes apart, such a call does not find the documents stored in a
304
+ scope;
305
+ - over a `FileDocumentStore` with `scopes`, every call but `sweep` throws a `DocumentScopeError` of
306
+ code `"scope_required"`. With `unscoped: "root"`, the documents go to the root folder without an
307
+ error, outside the chat's folder: removing that folder does not erase them;
308
+ - a `sweep` that drops it sweeps every scope: `files.sweep({ scope })` removes the expired
309
+ documents of every chat.
310
+
311
+ Pass every argument on:
312
+
313
+ ```ts
314
+ import type { DocumentContext, DocumentStore, StoredDocument } from "llm-large-files";
315
+
316
+ /** Logs the time of each read of metadata, and passes every method and argument on: the context too. */
317
+ export function timed(inner: DocumentStore): DocumentStore {
318
+ return {
319
+ put: (document: StoredDocument, context?: DocumentContext) => inner.put(document, context),
320
+ get: (id, context) => inner.get(id, context),
321
+ getMeta: async (id, context) => {
322
+ const started = performance.now();
323
+ try {
324
+ return await inner.getMeta(id, context);
325
+ } finally {
326
+ console.info(`getMeta took ${Math.round(performance.now() - started)} ms`);
327
+ }
328
+ },
329
+ delete: (id, context) => inner.delete(id, context),
330
+ // The optional methods, each only when the inner store has it: the library checks for them.
331
+ ...(inner.sweep && { sweep: (now, context) => inner.sweep!(now, context) }),
332
+ ...(inner.readTextRange && { readTextRange: (id, start, end, context) => inner.readTextRange!(id, start, end, context) }),
333
+ ...(inner.putIndex && { putIndex: (id, index, context) => inner.putIndex!(id, index, context) }),
334
+ ...(inner.getIndex && { getIndex: (id, context) => inner.getIndex!(id, context) }),
335
+ ...(inner.putOriginal && { putOriginal: (id, bytes, context) => inner.putOriginal!(id, bytes, context) }),
336
+ ...(inner.getOriginal && { getOriginal: (id, context) => inner.getOriginal!(id, context) }),
337
+ };
338
+ }
339
+ ```
340
+
341
+ A subclass writes `super.getMeta(id, context)`, not `super.getMeta(id)`. A wrapper that leaves out
342
+ an optional method hides it from the library: without `readTextRange`, every document is loaded
343
+ whole; without `putOriginal` and `getOriginal`, the store keeps no copy of an upload for
344
+ `view_pages`; without `getIndex`, each opening of a document reads its whole text first, to build
345
+ its line index.
346
+
347
+ ### Use the context, or not
348
+
349
+ - `context.scope` can be the boundary of your storage: a key prefix, a folder, a filter on a
350
+ collection. `context.owner` lets you index the documents by user.
351
+ - A store that ignores the context still keeps the scopes apart for the library, through
352
+ `meta.scope`. The IDs your application gives must then be unique in the whole store: an ingest
353
+ under an ID that is taken in another scope is an `IngestError` `"exists"` (409).
354
+ - Which call carries which context, and the rules of a store, are in
355
+ [Writing a store of your own](./guides/storage.md#writing-a-store-of-your-own). In short: return
356
+ a field that was left out (`owner`, `scope`) absent, not `null`. Read an expired document as
357
+ missing, even when its removal fails. Throw a `DocumentScopeError` for a scope you cannot keep.
358
+
359
+ ### Write the record before the text
360
+
361
+ The storage guide's example `BlobDocumentStore` used to write the text, then insert the record
362
+ under a unique key. That was enough while every ID was the library's. With your application's IDs,
363
+ two servers can ingest one ID at the same moment: the ingest whose insert fails has then written
364
+ its text over the text of the one that won. The library reads that document as missing when the two
365
+ texts differ in length or in lines, read whole or by range. When they do not, it serves the loser's
366
+ text.
367
+
368
+ **What to do.** Insert the record first, hidden from `getMeta` until the text is written, as the
369
+ example now does
370
+ ([Example: object storage and a database](./guides/storage.md#example-object-storage-and-a-database)).
371
+ Two ingests of one ID that overlap then both fail with a 503, and nothing wrong is stored. With an
372
+ ID of its own for each upload, as `attach()` and the worked example below make, none of this
373
+ happens.
374
+
375
+ ### Allow the new fields
376
+
377
+ A schema that checks each field of what you store refuses the fields 0.9.0 adds: a MongoDB
378
+ `$jsonSchema` with `additionalProperties: false`, or a Mongoose schema in strict mode that throws.
379
+ Over the metadata of a store of yours, every ingest then fails with a 503 "The document could not
380
+ be stored (…). Try again.", and so does every retry. Over the rounds you keep, your own insert
381
+ fails. Change the schema before the first server of 0.9.0 starts:
382
+
383
+ ```ts
384
+ import { MongoClient } from "mongodb";
385
+
386
+ const mongo = new MongoClient(process.env.MONGODB_URI!);
387
+ const db = mongo.db("chat");
388
+
389
+ export async function allowNewFields(): Promise<void> {
390
+ // A collection of DocumentMeta (a store of your own), checked by a $jsonSchema without other fields.
391
+ await db.command({
392
+ collMod: "documents",
393
+ validator: {
394
+ $jsonSchema: {
395
+ bsonType: "object",
396
+ additionalProperties: false,
397
+ properties: {
398
+ _id: {},
399
+ // ...the fields your schema already has, then those of 0.9.0:
400
+ metaVersion: { bsonType: "number" },
401
+ scope: { bsonType: "array", items: { bsonType: "string" } },
402
+ sha256: { bsonType: "string" },
403
+ original: {
404
+ bsonType: "object",
405
+ properties: { ref: { bsonType: "string" }, bytes: { bsonType: "number" }, sha256: { bsonType: "string" } },
406
+ },
407
+ },
408
+ },
409
+ },
410
+ });
411
+ // The rounds you keep with each question: a round gets `version`.
412
+ await db.command({
413
+ collMod: "turns",
414
+ validator: {
415
+ $jsonSchema: {
416
+ bsonType: "object",
417
+ properties: {
418
+ toolTurns: {
419
+ bsonType: "array",
420
+ items: {
421
+ bsonType: "object",
422
+ additionalProperties: false,
423
+ required: ["role", "calls"],
424
+ properties: { role: { enum: ["tools"] }, version: { bsonType: "number" }, calls: { bsonType: "array" } },
425
+ },
426
+ },
427
+ },
428
+ },
429
+ },
430
+ });
431
+ }
432
+ ```
433
+
434
+ Keep every field of `meta`, including those your store does not know: later versions add more.
435
+
436
+ ### Check the store
437
+
438
+ `documentStoreChecks` of `llm-large-files/testing` runs the checks a store must pass, in Vitest,
439
+ Jest or `node:test`. With `isolatesScopes`, it checks that one ID in two scopes is two documents
440
+ on every method: a wrapper that drops the context fails there
441
+ ([Checking a store](./reference/testing.md#checking-a-store)).
442
+
443
+ ## Several servers and rolling deploys
444
+
445
+ During a rolling deploy, servers of 0.8 and 0.9 share the store and answer the same chats. What a
446
+ server of 0.8 does with what 0.9.0 wrote:
447
+
448
+ | What 0.9.0 wrote | A server of 0.8 |
449
+ |---|---|
450
+ | A document in the flat layout of `FileDocumentStore`, under a library ID (`doc_…`) | Reads it, and ignores `metaVersion` and `sha256`. |
451
+ | A document under an application's ID | Finds it missing, over any store: it takes only `doc_` IDs. |
452
+ | A document in the folders of a `FileDocumentStore` with `scopes` | Finds it missing: it does not look there. |
453
+ | A document with a scope, in a store that ignores the context (the flat layout, a store of yours written for 0.8) | Serves it to its owner in any scope: it does not check `meta.scope`. |
454
+ | An original kept by reference | Takes it for kept, but the store has no copy: its `view_pages` answers that the original file is no longer on the server. |
455
+ | A file written `0600` | Cannot read it when it runs as another user. |
456
+ | A stored round with `version: 1` | Reads it, and ignores the field. |
457
+
458
+ 0.9.0 reads what 0.8 wrote, as before. Documents of 0.8 have no `metaVersion` and no `sha256`: a
459
+ kept copy is checked by its size alone. They have no scope either: under `requireScope` they read
460
+ as missing, and a `FileDocumentStore` with `scopes` looks for them only in the folder of the
461
+ call's scope.
462
+
463
+ So upgrade in two steps:
464
+
465
+ 1. **First the package, with your settings as they are.** Before that, change the schemas that
466
+ refuse new fields ([above](#allow-the-new-fields)), and set `fileMode` and `directoryMode` if
467
+ servers or jobs run as other users. During this deploy, servers of both versions read each
468
+ other's documents.
469
+ 2. **Then the new settings,** once no server of 0.8 is left: `scopes`, application IDs, originals
470
+ by reference, `requireOwner` and `requireScope`. A server with the old settings does not find
471
+ the documents of the new ones. Deploy them to every server at once (blue-green), or keep each
472
+ chat on servers of one setting until the deploy ends.
473
+
474
+ Run the sweep from a server of 0.9.0. One of 0.8 does not go into the folders of a store with
475
+ `scopes`, and leaves the files of application IDs alone. More on several servers is in
476
+ [Deployment](./guides/deployment.md#servers-of-two-versions).
477
+
478
+ From 0.9.0 on, `metaVersion` and `ToolTurn.version` protect what a later version writes: 0.9.0
479
+ refuses it ([above](#data-written-by-a-newer-version)), where 0.8 ignores both fields.
480
+
481
+ ## A worked example: a Hebrew chatbot on Gemini, MongoDB and a shared volume
482
+
483
+ A chatbot for Hebrew-speaking users answers with Gemini on Vertex AI. It keeps its chats in
484
+ MongoDB: one record per chat with its files, and one per question with its tool rounds. Several
485
+ pods mount one volume over NFS, with a folder per user and chat.
486
+
487
+ **Before, on 0.8.2,** each request made a library for its chat, over a store in the chat's folder.
488
+ The limits of 0.8.2 (`maxConcurrentIngests`, `cacheBytes`, `maxConcurrentScans`) then held for each
489
+ chat, not for the pod. Each PDF was kept twice: the upload the app saved, and a copy in the store.
490
+ The app kept a lookup of where each `doc_` ID lived.
491
+
492
+ ```ts
493
+ // Before (0.8.2): a library for each chat, each with a store over the chat's folder.
494
+ const filesOf = (userId: string, sessionId: string) =>
495
+ createLargeFiles({
496
+ store: new FileDocumentStore(path.join(VOLUME, userId, sessionId)),
497
+ keepOriginals: ["pdf"], // a second copy of each PDF, as <id>.bin
498
+ });
499
+ ```
500
+
501
+ **After, on 0.9.0,** one library serves the whole pod. The store keeps each chat's files in the
502
+ chat's folder. Each upload is saved once, by the upload handler, in the chat's `uploads` folder,
503
+ under an ID the app makes. The library reads it there for `view_pages`, and the store keeps no
504
+ copy. The ID is the document's ID, so the chat's record needs no lookup.
505
+
506
+ ```text
507
+ /mnt/documents/
508
+ h3f9a…/ the user: a hash of the user's ID
509
+ 65a1f0c2e4b0a1b2c3d4e5f6/ the chat: its MongoDB ObjectId
510
+ .llm-large-files/ the store's files: up-1c2d….json, .txt, .idx
511
+ uploads/ the uploads: up-1c2d…, the PDF as the user sent it
512
+ ```
513
+
514
+ ### The documents and the uploads
515
+
516
+ ```ts
517
+ // documents.ts: one library for the process, the same on every pod.
518
+ import { randomUUID } from "node:crypto";
519
+ import { mkdir, rm } from "node:fs/promises";
520
+ import path from "node:path";
521
+ import { MongoClient } from "mongodb";
522
+ import { createLargeFiles, FileDocumentStore, hashedScopeSegment, isSafeScopeSegment, type DocumentScope, type ToolTurn } from "llm-large-files";
523
+ import { createDocumentHandlers, fileOriginals } from "llm-large-files/node";
524
+
525
+ // The volume every pod mounts (NFS, with lookupcache=positive).
526
+ const VOLUME = process.env.DOCUMENTS_DIR ?? "/mnt/documents";
527
+
528
+ /** A chat, with the files attached to it. `_id` is a MongoDB ObjectId in hex. */
529
+ type ChatFile = { id: string; name: string; sha256?: string };
530
+ export type SessionRecord = { _id: string; userId: string; files: ChatFile[] };
531
+ /** One question of a chat, with the tool rounds that answered it. */
532
+ export type TurnRecord = { sessionId: string; index: number; question: string; toolTurns: ToolTurn[]; answer?: string; createdAt: Date };
533
+
534
+ const mongo = new MongoClient(process.env.MONGODB_URI!);
535
+ export const db = mongo.db("chat");
536
+ export const sessions = db.collection<SessionRecord>("sessions");
537
+ export const turns = db.collection<TurnRecord>("turns");
538
+
539
+ export const files = createLargeFiles({
540
+ // <VOLUME>/<user>/<session>/.llm-large-files/: the store's files of each chat.
541
+ store: new FileDocumentStore(VOLUME, { scopes: { depth: 2 } }),
542
+ keepOriginals: ["pdf"], // so that view_pages can look at the pages of a PDF
543
+ originals: fileOriginals(VOLUME), // the uploads, read where the handler saved them
544
+ ttlMs: Infinity, // a chat's documents stay as long as the chat
545
+ requireOwner: true,
546
+ requireScope: true,
547
+ });
548
+
549
+ /**
550
+ * The scope of a chat, which is also its folder. A user ID from the sign-in may have capitals or
551
+ * an "@", so its folder is its hash. A session ID is an ObjectId: lowercase hex.
552
+ */
553
+ export function scopeOf(userId: string, sessionId: string): DocumentScope {
554
+ if (!isSafeScopeSegment(sessionId)) throw new TypeError("This is not a session ID.");
555
+ return [hashedScopeSegment(userId), sessionId];
556
+ }
557
+
558
+ /** Makes a chat's folders: call it when you create the chat's record, not on each upload. */
559
+ export async function startChat(userId: string, sessionId: string): Promise<void> {
560
+ await mkdir(path.join(VOLUME, ...scopeOf(userId, sessionId), "uploads"), { recursive: true, mode: 0o700 });
561
+ }
562
+
563
+ /**
564
+ * Deletes a chat, once its questions are stopped: its record first, so that no upload starts, then
565
+ * its questions, whose rounds hold excerpts, then its folder (the store's files and the uploads).
566
+ */
567
+ export async function deleteChat(userId: string, sessionId: string): Promise<void> {
568
+ const { deletedCount } = await sessions.deleteOne({ _id: sessionId, userId });
569
+ if (deletedCount === 0) return; // not this user's chat, or deleted already
570
+ await turns.deleteMany({ sessionId });
571
+ // An upload being stored now can write into the folder while rm empties it: rm then looks again.
572
+ await rm(path.join(VOLUME, ...scopeOf(userId, sessionId)), { recursive: true, force: true, maxRetries: 5 });
573
+ }
574
+
575
+ const chatGone = () => Object.assign(new Error("This chat no longer exists."), { status: 404 });
576
+
577
+ export const documents = createDocumentHandlers(files, {
578
+ // Your sign-in: undefined answers 401 "Sign in first." under requireOwner.
579
+ getOwner: (request) => userIdOf(request),
580
+ // The chat comes in a header. Only the user's own chats.
581
+ getScope: async (request) => {
582
+ const userId = userIdOf(request)!;
583
+ const sessionId = String(request.headers["x-session-id"] ?? "");
584
+ if (!isSafeScopeSegment(sessionId) || !(await sessions.findOne({ _id: sessionId, userId }))) throw chatGone();
585
+ return scopeOf(userId, sessionId);
586
+ },
587
+ // Before the body is read: the ID, where the body is saved, and the ref that fileOriginals reads.
588
+ prepareUpload: (_request, { scope }) => {
589
+ const id = `up-${randomUUID().replaceAll("-", "")}`;
590
+ const ref = [...scope!, "uploads", id].join("/"); // <user>/<session>/uploads/<id>
591
+ return { id, path: path.join(VOLUME, ref), original: { ref } };
592
+ },
593
+ // Once it is stored, the chat lists it. Throw, and the document and the saved file are removed.
594
+ onUploaded: async (document, { owner, scope }) => {
595
+ const file: ChatFile = { id: document.id, name: document.name, ...(document.sha256 ? { sha256: document.sha256 } : {}) };
596
+ const { matchedCount } = await sessions.updateOne({ _id: scope![1]!, userId: owner! }, { $push: { files: file } });
597
+ if (matchedCount === 0) throw chatGone();
598
+ },
599
+ // The library never removes the saved file: remove it with the document.
600
+ onRemoved: async (id, { owner, scope }) => {
601
+ await sessions.updateOne({ _id: scope![1]!, userId: owner! }, { $pull: { files: { id } } });
602
+ await rm(path.join(VOLUME, ...scope!, "uploads", id), { force: true });
603
+ },
604
+ });
605
+ ```
606
+
607
+ `userIdOf(request)` is your sign-in: it gives the user's ID, or `undefined`. Mount
608
+ `documents.upload`, `documents.get` and `documents.remove` as in
609
+ [Web app](./guides/web-app.md#uploads-with-createdocumenthandlers).
610
+
611
+ - **One library, one store, every pod the same.** Each pod makes this library once. Its limits
612
+ then hold for the pod, whatever the number of chats. Every pod opens its store over the same
613
+ folder with the same options.
614
+ - **The folders.** The chat's folder and its `uploads` are made when the chat is. The store makes
615
+ only its own folder, `.llm-large-files`, inside the chat's. The handler makes no folder.
616
+ `fileOriginals` reads no file through a link in its folders, so the handler refuses such a path
617
+ before it writes: 500 "Upload failed (ELOOP).". Mount another disk at the volume's path rather
618
+ than link to it.
619
+ - **The user's folder is a hash.** A scope segment names a folder, so it must be lowercase letters,
620
+ digits, `_` and `-` (`isSafeScopeSegment`). `hashedScopeSegment` turns any ID into one: `h` and 40
621
+ hex digits. The owner stays the user's ID itself.
622
+ - **The ID.** `prepareUpload` makes the document's ID. It is random, so it cannot be guessed, and
623
+ it holds nothing about the user: the model sees it.
624
+ - **The file is saved once.** The handler writes the body to `uploads/<id>` as it arrives, under
625
+ `uploadIdleTimeoutMs`, and ingests it from there at its turn. It is not held in memory while it
626
+ waits. When the upload fails for any reason, the file is removed. A server that is killed in the
627
+ middle of an upload cannot remove it: see
628
+ [Stopping a server](./guides/deployment.md#stopping-a-server).
629
+ - **`onUploaded` records the ID** before the browser gets its 201. When it throws, the document and
630
+ the file are removed, and the browser gets the error. It has no time limit: give your database a
631
+ timeout of its own.
632
+ - **`ttlMs: Infinity`.** A document that expired would be removed without a call to `onRemoved`,
633
+ and would leave its upload and its line in the chat's record. So the documents stay as long as
634
+ the chat, and go with it.
635
+ - **Deleting a chat.** `deleteChat` removes the record first: `getScope` then refuses a new upload
636
+ with a 404. An upload already under way fails, with a 404 "This chat no longer exists." or a 500:
637
+ the store does not make the chat's folder again (`createScopeFolders` is off by default). An
638
+ upload being stored at that moment can still write its files into the folder while `rm` empties
639
+ it, and `rm` then fails with `ENOTEMPTY`. `maxRetries` makes `rm` look again and remove them. The
640
+ questions go before the folder, so if `rm` still fails, only files are left, in a folder that no
641
+ chat has: a cleanup job can remove them.
642
+ - **Several pods.** Each upload's ID is new, so two pods never write one document. A question can
643
+ run on another pod than its upload: each use asks the store first. Run the sweep from one pod, or
644
+ from a scheduled job ([Deployment](./guides/deployment.md#sweeping-expired-documents)). With
645
+ `ttlMs: Infinity` it removes no document, only what a failed delete or upload left behind.
646
+ - **Another user on the volume.** The store writes files `0600` in folders `0700`, the handler
647
+ writes the uploads `0600` (`uploadFileMode`), and `startChat` makes its folders `0700`. If a backup
648
+ job runs as another user of the pods' group, give the store `fileMode: 0o640` and
649
+ `directoryMode: 0o750`, the handler `uploadFileMode: 0o640`, and `startChat` `mode: 0o750`.
650
+ - **The documents of 0.8** stay in the old folders, named by the user's ID itself, and the new
651
+ store does not look there. Ingest them again when a question needs them
652
+ ([Moving the documents of 0.8](#moving-the-documents-of-08)).
653
+
654
+ ### Questions, with errors in Hebrew
655
+
656
+ ```ts
657
+ // ask.ts: a question of a chat, answered by Gemini on Vertex AI, with errors in Hebrew.
658
+ import { GoogleAuth } from "google-auth-library";
659
+ import { errorInfoOf, partialResultOf, type ChatTurn, type ErrorInfo, type ToolTurn } from "llm-large-files";
660
+ import { askGemini, vertexAi } from "llm-large-files/gemini";
661
+ import { files, scopeOf, sessions, turns, type TurnRecord } from "./documents.js";
662
+
663
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
664
+ const endpoint = vertexAi({
665
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
666
+ model: "gemini-3.8-flash",
667
+ accessToken: async () => (await auth.getAccessToken())!,
668
+ });
669
+
670
+ /** The messages of the next question: each earlier question, its tool rounds, its answer. */
671
+ function historyOf(earlier: TurnRecord[], question: string): Array<ChatTurn | ToolTurn> {
672
+ return [
673
+ ...earlier.flatMap((turn): Array<ChatTurn | ToolTurn> => [
674
+ { role: "user", text: turn.question },
675
+ ...turn.toolTurns,
676
+ ...(turn.answer !== undefined ? [{ role: "assistant" as const, text: turn.answer }] : []),
677
+ ]),
678
+ { role: "user", text: question },
679
+ ];
680
+ }
681
+
682
+ export type Answer = { status: number; text?: string; missing?: string[]; error?: string; retryAfterMs?: number };
683
+
684
+ export async function ask(userId: string, sessionId: string, question: string, signal: AbortSignal): Promise<Answer> {
685
+ const session = await sessions.findOne({ _id: sessionId, userId });
686
+ if (!session) return { status: 404, error: "השיחה הזו כבר לא קיימת." };
687
+ const earlier = await turns.find({ sessionId }).sort({ index: 1 }).toArray();
688
+ const asked = { sessionId, index: earlier.length, question, createdAt: new Date() };
689
+ try {
690
+ const result = await askGemini({
691
+ files,
692
+ endpoint,
693
+ owner: userId,
694
+ scope: scopeOf(userId, sessionId),
695
+ documentIds: session.files.map((file) => file.id),
696
+ messages: historyOf(earlier, question),
697
+ onMissingDocuments: "drop", // a file deleted in another tab: answer without it
698
+ signal,
699
+ });
700
+ if (result.missing?.length) {
701
+ await sessions.updateOne({ _id: sessionId, userId }, { $pull: { files: { id: { $in: result.missing } } } });
702
+ }
703
+ await turns.insertOne({ ...asked, toolTurns: result.toolTurns, ...(result.answered ? { answer: result.text } : {}) });
704
+ return { status: 200, text: result.text, missing: result.missing ?? [] };
705
+ } catch (error) {
706
+ // What a failed question read is kept, so that the next one need not read it again.
707
+ const partial = partialResultOf(error);
708
+ if (partial) await turns.insertOne({ ...asked, toolTurns: partial.toolTurns });
709
+ console.error("A question failed", error); // the provider's words are for your log
710
+ const info = errorInfoOf(error);
711
+ return { status: info.status, error: hebrew(info), ...(info.retryAfterMs !== undefined ? { retryAfterMs: info.retryAfterMs } : {}) };
712
+ }
713
+ }
714
+
715
+ /** What to tell a Hebrew-speaking user. The whole table is in the errors guide. */
716
+ function hebrew(info: ErrorInfo): string {
717
+ switch (info.category) {
718
+ case "store":
719
+ return "לא ניתן לגשת לקבצים כרגע. נסו שוב בעוד רגע.";
720
+ case "missing":
721
+ return info.code === "scope_missing" ? "השיחה הזו כבר לא קיימת." : "אחד הקבצים כבר לא זמין. צרפו אותו שוב.";
722
+ case "model":
723
+ switch (info.code) {
724
+ case "context_overflow": return "השיחה ארוכה מדי. פתחו שיחה חדשה, או שאלו על פחות קבצים.";
725
+ case "rate_limit": return "העוזר עמוס כרגע. נסו שוב בעוד דקה.";
726
+ case "timeout": return "התשובה התעכבה יותר מדי. נסו שוב.";
727
+ default: return "לא ניתן לקבל תשובה כרגע. נסו שוב.";
728
+ }
729
+ case "aborted":
730
+ return "השאלה נעצרה.";
731
+ default:
732
+ return "משהו השתבש. נסו שוב מאוחר יותר.";
733
+ }
734
+ }
735
+ ```
736
+
737
+ - **The same owner and scope** as the upload: a document of another chat is missing here, even
738
+ for the same user.
739
+ - **The rounds are kept** with each question, as `toolTurns`, each with `version: 1`. If the
740
+ `turns` collection has a schema, it must allow that field ([above](#allow-the-new-fields)).
741
+ - **`onMissingDocuments: "drop"`** answers without a file that was deleted meanwhile, and lists it
742
+ in `result.missing`, which the chat's record then drops.
743
+ - **`errorInfoOf`** gives one record for any error: a `category`, a `code`, the status to answer
744
+ with, and when to try again. The words for the user are yours. The whole table is in
745
+ [Errors and reliability](./guides/errors-and-reliability.md#your-users-words-errorinfoof), with
746
+ the events of a streamed answer.
747
+ - **Nothing private reaches the model.** The owner, the scope, the ref of each upload and its
748
+ SHA-256 are kept for the server. The model sees the file's name, its ID and its text.
749
+
750
+ ### The page
751
+
752
+ The upload handlers answer in English. Their JSON answer is `{ "error": "…" }`, and its status
753
+ says enough to tell the user in Hebrew:
754
+
755
+ ```ts
756
+ /** Sends a file to the chat, and gives its ID, or the words to show in Hebrew. */
757
+ export async function attach(sessionId: string, file: File): Promise<{ id: string } | { error: string }> {
758
+ const response = await fetch("/api/documents", {
759
+ method: "POST",
760
+ headers: { "Content-Type": "application/octet-stream", "X-File-Name": encodeURIComponent(file.name), "X-Session-Id": sessionId },
761
+ body: file,
762
+ });
763
+ if (response.ok) return { id: ((await response.json()) as { id: string }).id };
764
+ return { error: uploadError(response.status, response.headers.get("Retry-After")) };
765
+ }
766
+
767
+ /** The upload handlers answer in English: the status says enough for the user. */
768
+ function uploadError(status: number, retryAfter: string | null): string {
769
+ switch (status) {
770
+ case 401: return "יש להתחבר מחדש.";
771
+ case 404: return "השיחה הזו כבר לא קיימת.";
772
+ case 408: return "ההעלאה נקטעה. נסו שוב.";
773
+ case 413: return "הקובץ גדול מדי.";
774
+ case 422: return "לא ניתן לקרוא את הקובץ. ייתכן שהוא פגום, סרוק או מסוג שאינו נתמך.";
775
+ case 503: return `השרת עמוס כרגע. נסו שוב בעוד ${retryAfter ?? "כמה"} שניות.`;
776
+ default: return "ההעלאה נכשלה. נסו שוב מאוחר יותר.";
777
+ }
778
+ }
779
+ ```
780
+
781
+ Set `dir="rtl"` (or `dir="auto"`) on the element that shows these words, so that a file name in
782
+ Latin letters stays in its place. An upload with progress (`Accept: text/event-stream`) ends with
783
+ `ingest.error`, whose `code` tells more: `"too_large"`, `"no_text"`, `"encrypted"`
784
+ ([Web app](./guides/web-app.md#upload-with-progress)).
785
+
786
+ ## Moving the documents of 0.8
787
+
788
+ Documents of 0.8 have no scope. Pick a way by the layout they are in.
789
+
790
+ - **A library per chat, each over `FileDocumentStore(<root>/<user>/<chat>)`.** Their files are in
791
+ the chat's folder itself. `scopes: { depth: 2, folder: "" }` reads them there, in place, as long
792
+ as `requireScope` is off and the names of the folders pass `isSafeScopeSegment`. Your own files
793
+ then sit beside the store's: keep them in a subfolder, such as `uploads/`
794
+ ([Storage](./guides/storage.md#files-in-a-folder-per-user-or-per-chat)).
795
+ - **One flat folder, `FileDocumentStore(<root>)`.** `scopes: { depth: 2, unscoped: "root" }` reads
796
+ them from `<root>` for a call without a scope, as before, until they expire. New chats are asked
797
+ with a scope, old ones without, and `requireScope` stays off.
798
+ - **Ingest them again, when a question needs them.** The new store does not find an old `doc_` ID
799
+ in the chat's scope, so the question calls `onMissingDocuments`. Ingest the file again from the
800
+ upload you kept, under a new ID in the chat's scope, and return `{ replace: { [oldId]: newId } }`.
801
+ Then put the new ID in the chat's record, in place of the old one. This works with
802
+ `requireScope` on. Earlier stored rounds still name the old ID: the model reads the file again
803
+ under the new one.
804
+
805
+ ```ts
806
+ import { askWithFiles, IngestError, type AskResult, type LargeFiles, type MissingDocumentsAction, type ModelAdapter } from "llm-large-files";
807
+
808
+ declare const files: LargeFiles;
809
+ declare const model: ModelAdapter;
810
+ // Your records of the uploads of 0.8: where each doc_ ID's file was saved.
811
+ declare const keptUploads: { find(userId: string, documentId: string): Promise<{ name: string; path: string } | undefined> };
812
+ declare const chats: { renameFiles(sessionId: string, replace: Record<string, string>): Promise<void> };
813
+
814
+ export async function askMoving(userId: string, sessionId: string, documentIds: string[], question: string): Promise<AskResult> {
815
+ return askWithFiles({
816
+ files,
817
+ model,
818
+ owner: userId,
819
+ scope: [userId, sessionId],
820
+ documentIds,
821
+ messages: [{ role: "user", text: question }],
822
+ onMissingDocuments: async (missing, { owner, scope }): Promise<MissingDocumentsAction> => {
823
+ const replace: Record<string, string> = {};
824
+ for (const oldId of missing) {
825
+ const upload = await keptUploads.find(userId, oldId);
826
+ if (!upload) continue; // gone for good
827
+ const newId = `up-${oldId.slice(4)}`;
828
+ try {
829
+ await files.ingest({ name: upload.name, source: { path: upload.path }, owner, scope, id: newId });
830
+ } catch (error) {
831
+ // Another question of the chat ingested it meanwhile.
832
+ if (!(IngestError.is(error) && error.code === "exists")) throw error;
833
+ }
834
+ replace[oldId] = newId;
835
+ }
836
+ await chats.renameFiles(sessionId, replace);
837
+ // All back: plan again with the new IDs. Otherwise answer without those still missing.
838
+ return Object.keys(replace).length === missing.length ? { replace } : "drop";
839
+ },
840
+ });
841
+ }
842
+ ```
843
+
844
+ - The new ID is made from the old one, so two questions that meet the same old ID at once make one
845
+ document. The second ingest gets `"exists"`. If the first has not stored it yet, that question
846
+ fails with `DocumentsNotFoundError`, and can be asked again.
847
+ - `{ replace }` plans the question again once. An ID still missing then fails the question with
848
+ `DocumentsNotFoundError`. With `"drop"`, the question is answered without the files still
849
+ missing, and the files ingested again are used from the next question, under their new IDs
850
+ ([missing documents](./reference/ask.md#missing-documents)).
851
+
852
+ ## What did not change
853
+
854
+ - **The text sent to the model,** for ordinary chats: the tool guide, the tool descriptions, the
855
+ cards and the instructions are those of 0.8.2. So the provider's prompt cache does not miss at
856
+ the upgrade. Text is new only when its case happens:
857
+ - the line for documents left out under `onMissingDocuments: "drop"`;
858
+ - the busy answer of `view_pages`;
859
+ - its answers for a file kept by reference that changed, and for a PDF the store did not return
860
+ in time;
861
+ - a document ingested under your ID is named by that ID, where the model saw `doc_…`;
862
+ - a right-to-left PDF table ingested from 0.9.0 on can read in another order (LLF-037 in the
863
+ changelog). Documents ingested before keep their text;
864
+ - Gemini `contents` that 0.5.0 converted ([above](#gemini-contents)).
865
+ - **The store interface.** No method is new, and none is required that was not.
866
+ - **The flat layout of `FileDocumentStore`:** the names of its files, and their format.
867
+ - **The shape of `toolTurns`**, apart from `version`: a round of 0.8 is read as before.
868
+
869
+ ## New and optional
870
+
871
+ - **Owners and scopes:** `requireOwner`, `requireScope`, `IngestInput.scope`, `AccessOptions.scope`,
872
+ `AskOptions.scope` and `ToolOptions.access` ([Storage](./guides/storage.md#owners-and-scopes)).
873
+ - **Application IDs:** `IngestInput.id` and `ifExists` ([Storage](./guides/storage.md#application-ids)).
874
+ - **A folder per user and chat:** `FileDocumentStore` with `scopes`, `isSafeScopeSegment` and
875
+ `hashedScopeSegment` ([Storage](./guides/storage.md#files-in-a-folder-per-user-or-per-chat)).
876
+ - **The uploads your application keeps:** `original: { ref }`, `originals` and `fileOriginals`
877
+ ([Storage](./guides/storage.md#the-file-your-application-keeps)).
878
+ - **Ingest from a path:** `files.ingest({ name, source: { path } })`
879
+ ([library](./reference/library.md#ingestfromsource)).
880
+ - **The upload handlers:** `getScope`, `prepareUpload`, `onUploaded`, `onRemoved`, `uploadSpool`
881
+ and `uploadAnswerOf` ([Web app](./guides/web-app.md#uploads-with-createdocumenthandlers)).
882
+ - **Missing documents:** `onMissingDocuments` ([ask](./reference/ask.md#missing-documents)).
883
+ - **Your users' words:** `errorInfoOf`, with a table in Hebrew
884
+ ([Errors and reliability](./guides/errors-and-reliability.md#your-users-words-errorinfoof)).
885
+ - **Looks at pages:** `maxConcurrentPageLooks` and `pageLookWaitMs` ([PDFs](./guides/pdfs.md#view_pages)).
886
+ - **Gemini histories:** `fromGeminiContents(contents, { rounds })`
887
+ ([gemini](./reference/gemini.md#fromgeminicontentscontents-options)).
888
+ - **The same file twice:** `meta.sha256`, for your app to compare. The library does not dedupe.
889
+ - **Tests:** `llm-large-files/testing`, with `fakeModel`, `fakeFetch`, test documents and
890
+ `documentStoreChecks` ([Testing](./reference/testing.md)).