llm-large-files 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,731 @@
1
+ # Storage
2
+
3
+ Where your documents live, who may use them, and for how long. This guide covers the two stores
4
+ that come with the library, owners and a layout per user and per chat, retention, keeping the
5
+ uploaded files, the contract a store of your own must meet, and the memory cache in front of the
6
+ store. The signatures of everything named here are in [the library reference](../reference/library.md).
7
+
8
+ ## What a store holds
9
+
10
+ `files.ingest` turns an upload into a document and hands it to the store, which keeps up to four
11
+ parts under the document's ID:
12
+
13
+ | Part | What it is | Written |
14
+ |---|---|---|
15
+ | Metadata | `DocumentMeta`: owner, file name, format, sizes, lines, outline, log profile, `createdAt`, `expiresAt`. | Always, last. |
16
+ | Text | The extracted text, normalized, as one string. | Always. |
17
+ | Line index | Where each line starts, in bytes and in characters: about 8 bytes a line. With it, a document read by range is opened without first reading all of its text. | When the store has `putIndex`. |
18
+ | Original | The uploaded file, byte for byte. | When `keepOriginals` lists the format and the store has `putOriginal`. |
19
+
20
+ The library makes the ID: `doc_` and 32 hexadecimal digits of a random UUID. It is new at every
21
+ ingest and never reused. `DOCUMENT_ID_PATTERN` (`/^doc_[a-f0-9]{32}$/`) matches it, and
22
+ `isDocumentId(value)` tests a value against it: use it on IDs that arrive in a request before they
23
+ reach your database. The library tests every ID itself before it asks the store. An ID that does
24
+ not match counts as missing, so a store only ever receives IDs that match.
25
+
26
+ A store holds documents, not conversations. The tool rounds of a conversation (`toolTurns`) hold
27
+ excerpts of the files, and keeping them is up to you: see [Conversations](./conversations.md).
28
+
29
+ ## Choosing a store
30
+
31
+ | Store | Use it for | Survives a restart | Several servers | Reads large files by range |
32
+ |---|---|---|---|---|
33
+ | `MemoryDocumentStore` | Tests, scripts, a demo in one process. | No | No | No |
34
+ | `FileDocumentStore` | One server, or several on a shared volume. | Yes | On a shared volume | Yes |
35
+ | Your own | A database and object storage, or what your platform has ([below](#writing-a-store-of-your-own)). | Up to you | Up to you | When it has `readTextRange` |
36
+
37
+ ```ts
38
+ import { createLargeFiles, FileDocumentStore, MemoryDocumentStore } from "llm-large-files";
39
+
40
+ // A server: one directory, kept across restarts. Several servers can share it on one volume.
41
+ export const files = createLargeFiles({ store: new FileDocumentStore(process.env.DOCUMENTS_DIR!) });
42
+
43
+ // Tests and scripts: everything is gone when the process ends.
44
+ export const scratch = createLargeFiles({ store: new MemoryDocumentStore() });
45
+ ```
46
+
47
+ ### `MemoryDocumentStore`
48
+
49
+ `new MemoryDocumentStore({ now })` keeps everything in the memory of the process.
50
+
51
+ - It has no `readTextRange`: every document is loaded whole, whatever its size.
52
+ - It keeps originals, as a copy of the uploaded bytes.
53
+ - `get` and `getMeta` remove a document that has expired when they are asked for it. `sweep`
54
+ removes every one that has.
55
+ - It copies the metadata it is given and the metadata it hands out, as a store that writes it
56
+ somewhere does: changing the `meta` that `ingest` or `getMeta` returned (deleting its `owner`
57
+ before you send it to a browser, say) changes nothing stored. Each call returns a new object.
58
+ `getOriginal` still returns the kept bytes themselves: treat them as read-only.
59
+ - `now` is its clock, `() => new Date()` by default. In a test, give the store and
60
+ `createLargeFiles({ now })` the same clock: see [Testing](./testing.md).
61
+
62
+ ### `FileDocumentStore`
63
+
64
+ `new FileDocumentStore(directory, { now, orphanAgeMs })` keeps each document as files in one
65
+ directory, which it creates at the first write. There are no subdirectories:
66
+
67
+ | File | Holds |
68
+ |---|---|
69
+ | `<id>.json` | The metadata, as JSON. The document exists while this file does. |
70
+ | `<id>.txt` | The text, as UTF-8. |
71
+ | `<id>.idx` | The line index: a 40-byte header, then 4 bytes for each line start in bytes and in characters, and for each passage and page start. About 6 MB for 730,000 lines. |
72
+ | `<id>.bin` | The uploaded file, with `keepOriginals`. |
73
+ | `<id>.<ext>.<8 hex digits>.tmp` | A file being written. It is renamed to its own name once complete. |
74
+
75
+ - Every file is written under a temporary name and then renamed, so no reader, on this server or
76
+ another one, sees half a file. A rename that meets `EPERM`, `EACCES` or `EBUSY` (on Windows,
77
+ another process has the file open for a moment) is tried again for up to about three seconds.
78
+ - `put` writes the text first and the metadata last. `delete` removes the metadata first, and
79
+ nothing else when that fails. A document never appears without its text, and is never listed once
80
+ its text is gone.
81
+ - Only IDs that match `DOCUMENT_ID_PATTERN` reach the file system. A read or a `delete` with another
82
+ ID finds nothing, and `put`, `putIndex` and `putOriginal` throw "Invalid document ID."
83
+ - A missing file means a missing document. Any other failure of a read (a volume that does not
84
+ answer, too many open files) is thrown, and the library passes it on as a `DocumentStoreError`.
85
+ There are two exceptions: an index file that cannot be read is built again from the text, and
86
+ `sweep` returns 0 when it cannot list the directory. A failed write or delete is thrown as it
87
+ came ([Errors](#errors)). Metadata that cannot be parsed counts as absent.
88
+ - `getMeta` removes a document that has expired, by the store's own clock (`now`).
89
+ - `readTextRange` reads only the bytes asked for, so a tool call never loads a large file whole.
90
+ The whole text is read only when the plan sends it in the prompt.
91
+ - `sweep` removes expired documents and returns how many. It also removes files that belong to no
92
+ document (an upload that failed, a server that stopped while writing) and temporary files, once
93
+ they are `orphanAgeMs` old, one hour by default: a younger one may be an upload in progress on
94
+ another server. A document whose metadata could not be read at all is left alone, whatever its
95
+ age. One that cannot be removed is left for the next sweep, and does not stop this one.
96
+ - The files are plain. The metadata names the owner, the file name, the headings and the log
97
+ message templates. A delete removes the files without overwriting them. If that matters, encrypt
98
+ the volume: see [Security](../security.md).
99
+
100
+ Several servers can share the directory on a network volume. What that needs, from where to run the
101
+ sweep to servers of two versions during an upgrade, is in [Deployment](./deployment.md).
102
+
103
+ ## Owners
104
+
105
+ ### How ownership works
106
+
107
+ Pass `owner` when you ingest a file, and the same owner on every later call. The library records it
108
+ in `meta.owner` and compares it, before every use, with the owner of the call:
109
+
110
+ ```ts
111
+ // `files` is your library, as in the sample above.
112
+ const bytes = new TextEncoder().encode("Clause 1. ...\nClause 2. ...\n");
113
+ const meta = await files.ingest({ name: "contract.txt", bytes, owner: "user-42" });
114
+
115
+ await files.getMeta(meta.id, { owner: "user-42" }); // the metadata
116
+ await files.getMeta(meta.id, { owner: "user-7" }); // undefined: as if it did not exist
117
+ await files.getMeta(meta.id); // undefined
118
+ await files.delete(meta.id, { owner: "user-7" }); // false: nothing is removed
119
+ await files.delete(meta.id, { owner: "user-42" }); // true
120
+ ```
121
+
122
+ | Call | Takes the owner as | A document of another owner |
123
+ |---|---|---|
124
+ | `files.ingest(input)` | `input.owner` | |
125
+ | `files.getMeta(id, access)` | `access.owner` | `undefined` |
126
+ | `files.getOriginal(id, access)` | `access.owner` | `undefined` |
127
+ | `files.delete(id, access)` | `access.owner` | `false`, and nothing is removed |
128
+ | `files.prepare(ids, base, options)` | `options.owner` | Listed in `missing`, and never read |
129
+ | `files.tools(documents, options)` | the `owner` of each `DocumentMeta` in `documents` (and in `viewPages`) | Each call that reads it answers `doc_… is no longer available on the server. Ask the user to attach the file again.` |
130
+ | `askWithFiles(options)`, `askGemini(options)` | `options.owner` | `DocumentsNotFoundError`, before any model request |
131
+ | `createDocumentHandlers(files, options)` | `options.getOwner(request)` | 404 "This file is no longer available." on GET; `{ "deleted": false }` on DELETE |
132
+
133
+ - An owner is a string that is not empty or only spaces. `ingest` throws a `TypeError` for `""`,
134
+ for spaces only and for `null`, which would make one owner shared by every caller without a
135
+ user: each could read and delete the documents of the others whose IDs it has. `user?.id ?? ""`
136
+ gives `""` to a caller who is not signed in. The message is
137
+ `owner must be a string that is not empty or only spaces, such as the signed-in user's ID. To let anyone with the document's ID use it, leave owner out.`
138
+ It throws the same for an owner from JavaScript that is neither a string nor a finite number,
139
+ such as the user object in place of its ID. A number is accepted, as before. Reads with
140
+ `owner: ""` work as before, so documents that 0.5.0 stored with that owner stay readable until
141
+ they expire.
142
+ - In `createDocumentHandlers`, a `getOwner` that returns such an owner is the server's mistake: the
143
+ upload is answered 500 `{ "error": "Upload failed (empty owner)." }` for `""`, spaces only or
144
+ `null`, and `{ "error": "Upload failed (owner is not a string)." }` for an object, a boolean,
145
+ `NaN` or an array, before its body is read. Nothing is logged. Where every upload needs a
146
+ signed-in user, throw an error with `status: 401` from `getOwner`; return `undefined` only where
147
+ anonymous uploads are meant (`user?.id || undefined`); and return the user's ID, not the user.
148
+ - A document of another owner looks exactly like one that does not exist, so a caller cannot learn
149
+ that an ID is in use.
150
+ - The comparison is exact (`===`): `"alice"` does not reach a document of `"Alice"` or of
151
+ `"alice/chat-1"`. There is no hierarchy and no wildcard.
152
+ - A document ingested without an owner can be used by anyone who has its ID, whether they pass an
153
+ owner or not. With signed-in users, always pass one. In `createDocumentHandlers`, a `getOwner` that
154
+ returns undefined makes an anonymous upload. To refuse a request without a user, throw from it with
155
+ a status ([Web app](./web-app.md)).
156
+ - The owner cannot be changed after ingest. Use a stable, opaque ID, not an email address that may
157
+ change.
158
+ - `files.tools(documents)` takes no owner option: it compares the owner stored with each document
159
+ with the `owner` of the metadata it is given, and answers a mismatch as a document that is gone
160
+ (`doc_… is no longer available on the server. …`). In a loop of your own, pass it only metadata
161
+ from `prepare(ids, base, { owner })` or `getMeta(id, { owner })`
162
+ ([Your own adapter and loop](./own-adapter-and-loop.md)). `askWithFiles` does this for you.
163
+
164
+ ### Choosing the owner string
165
+
166
+ The owner is any string you choose. The library has no notion of a chat or session, and cannot list
167
+ documents by owner. Two schemes work well:
168
+
169
+ | Owner | What the library enforces | What your application does |
170
+ |---|---|---|
171
+ | The user: `userId` | No user can use another user's documents. | Keeps each chat's document IDs in its session record and passes those, never a list from the browser as it came. A document can serve several chats of its user. |
172
+ | The user and the chat: `` `${userId}/${sessionId}` `` | A document can be used only in the chat it was uploaded to. | Builds the same string for every call: upload, questions, GET, DELETE. `getOwner` must then know the chat, from the URL or a header. A file used in two chats is uploaded twice. |
173
+
174
+ The [Conversations](./conversations.md) guide uses the first scheme. To switch to the second,
175
+ change the `owner` you pass, everywhere.
176
+
177
+ ### A layout per user and per chat
178
+
179
+ With chats kept as MongoDB records, as in [Conversations](./conversations.md)
180
+ (`{ _id, userId, documentIds }`, and one record per question in `turns`), the session record is the
181
+ list of a chat's documents:
182
+
183
+ ```ts
184
+ // chat-documents.ts. `files` is your library; `sessions` and `turns` are the collections of the
185
+ // Conversations guide.
186
+ import { toDocumentSummary, type DocumentSummary } from "llm-large-files";
187
+
188
+ /** Adds a file to a chat. The user owns it, and the session record lists it. */
189
+ export async function attach(userId: string, sessionId: string, file: { name: string; mimeType?: string; bytes: Uint8Array }): Promise<DocumentSummary> {
190
+ if (!await sessions.findOne({ _id: sessionId, userId })) throw new Error("No such chat.");
191
+ const meta = await files.ingest({ ...file, owner: userId });
192
+ try {
193
+ await sessions.updateOne({ _id: sessionId, userId }, { $addToSet: { documentIds: meta.id } });
194
+ } catch (error) {
195
+ // A document that no chat lists would stay until it expires.
196
+ await files.delete(meta.id, { owner: userId }).catch(() => undefined);
197
+ throw error;
198
+ }
199
+ return toDocumentSummary(meta);
200
+ }
201
+
202
+ /** The documents a question of this chat may use: all of the chat's, or those the user picked. */
203
+ export async function documentsFor(userId: string, sessionId: string, picked?: string[]): Promise<string[]> {
204
+ const session = await sessions.findOne({ _id: sessionId, userId });
205
+ if (!session) throw new Error("No such chat.");
206
+ return picked ? picked.filter((id) => session.documentIds.includes(id)) : session.documentIds;
207
+ }
208
+
209
+ /** Deletes a chat: its documents, its questions (their tool rounds hold excerpts), then the chat. */
210
+ export async function deleteChat(userId: string, sessionId: string): Promise<void> {
211
+ const session = await sessions.findOne({ _id: sessionId, userId });
212
+ if (!session) return;
213
+ for (const id of session.documentIds) await files.delete(id, { owner: userId });
214
+ await turns.deleteMany({ sessionId });
215
+ await sessions.deleteOne({ _id: sessionId, userId });
216
+ }
217
+ ```
218
+
219
+ - Ask with `owner: userId` and `documentIds: await documentsFor(userId, sessionId)`. When documents
220
+ have expired, the question throws `DocumentsNotFoundError` with their IDs:
221
+ [Conversations](./conversations.md) shows how to take them off the chat and ask the user for them
222
+ again.
223
+ - `files.delete` gives false for a document that has already expired or been deleted. There is
224
+ nothing left to do for it.
225
+ - If your application lets a document serve several chats, delete it only when no other chat lists
226
+ it.
227
+ - The `upload` handler of `createDocumentHandlers` answers the request itself, so it cannot record
228
+ the new ID in your session. Call `attach` from a route of your own, or record the ID the browser
229
+ sends back in a second request, after checking it with `files.getMeta(id, { owner })`. Routes are
230
+ in [Web app](./web-app.md).
231
+ - To delete everything of a user (an account that is closed), collect the IDs from the user's chats.
232
+ The library cannot find a user's documents. A store of your own can, if it keeps the owner where it
233
+ can query it, as the [example store](#example-object-storage-and-a-database) does.
234
+
235
+ ### Files in a folder per user or per chat
236
+
237
+ Every call but `put` gives a store the document ID without its metadata. `putOriginal` and
238
+ `putIndex` come before `put`, so a store cannot know the owner of a file it is writing.
239
+ A store therefore keys its files by document ID, and the layout by user and chat lives in your
240
+ database: the session record lists the IDs, and a store of your own can keep the owner next to each
241
+ document.
242
+
243
+ If your storage rules need each chat's files in a folder of their own, give each chat a library of
244
+ its own, over its own `FileDocumentStore`:
245
+
246
+ ```ts
247
+ import path from "node:path";
248
+ import { createLargeFiles, FileDocumentStore, type LargeFiles } from "llm-large-files";
249
+
250
+ // One case only: on a volume that ignores case, "Alice" and "alice" would be one folder.
251
+ const SAFE_ID = /^[a-z0-9_-]{1,64}$/;
252
+
253
+ /** The library of one chat: its files are in <DOCUMENTS_DIR>/<user>/<chat>/. */
254
+ export function filesOf(userId: string, sessionId: string): LargeFiles {
255
+ // The IDs become a path: refuse anything that could lead out of the directory.
256
+ if (!SAFE_ID.test(userId) || !SAFE_ID.test(sessionId)) throw new Error("Invalid user or chat ID.");
257
+ return createLargeFiles({
258
+ store: new FileDocumentStore(path.join(process.env.DOCUMENTS_DIR!, userId, sessionId)),
259
+ cacheBytes: 32 * 1024 * 1024, // each library has a cache of its own
260
+ });
261
+ }
262
+ ```
263
+
264
+ On a volume that ignores case (Windows, macOS, SMB shares), IDs that differ only in case would
265
+ share a folder, so the check takes lower case only. If your IDs are mixed case and unique
266
+ regardless of case, lower-case them before the check. IDs your database makes, such as UUIDs or
267
+ MongoDB ObjectIds in lower-case hex, pass it as they are.
268
+
269
+ What that costs:
270
+
271
+ - `cacheBytes` and `maxConcurrentScans` bound each library, not the process. A library made for one
272
+ request starts with an empty cache, so each question reads its documents from the store again.
273
+ - Each chat's folder needs a sweep of its own: `new FileDocumentStore(folder).sweep()` for each one.
274
+ The store never removes the folder itself.
275
+ - Deleting a chat is removing its folder, once no question of that chat is running.
276
+ - A document of another chat is not found: the folder is the boundary.
277
+
278
+ ## Retention
279
+
280
+ | Option | Default | What it does |
281
+ |---|---|---|
282
+ | `ttlMs` | 72 hours (259,200,000 ms) | How long a document is kept after it is ingested. `Infinity` keeps it until it is deleted. |
283
+
284
+ ```ts
285
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
286
+
287
+ export const files = createLargeFiles({
288
+ store: new FileDocumentStore(process.env.DOCUMENTS_DIR!),
289
+ ttlMs: 7 * 24 * 60 * 60 * 1000, // a week, in place of 72 hours
290
+ });
291
+
292
+ // Nothing runs the sweep for you. With several servers, one place is enough: see the Deployment guide.
293
+ setInterval(() => {
294
+ files.sweep().then(
295
+ (removed) => console.log(`sweep: ${removed} expired documents removed`),
296
+ (error: unknown) => console.error("sweep failed", error),
297
+ );
298
+ }, 60 * 60 * 1000).unref();
299
+ ```
300
+
301
+ - At ingest, `expiresAt` is set to `createdAt` plus `ttlMs`. It never changes: the library has no
302
+ call to extend it.
303
+ - From that instant the document counts as missing everywhere: `getMeta` and `getOriginal` give
304
+ undefined, `prepare` lists it in `missing`, and a question throws `DocumentsNotFoundError`. The
305
+ library checks `expiresAt` with its own clock before every use, whether or not the store has
306
+ removed the files yet.
307
+ - `ttlMs: Infinity`, or a time to live that runs past the year 9999, sets `expiresAt` to
308
+ `NEVER_EXPIRES`: `"9999-12-31T23:59:59.999Z"`. It is a date like any other, so every comparison,
309
+ and a server of an older version, reads it without a special case. `meta.expiresAt ===
310
+ NEVER_EXPIRES` tells you a document never expires.
311
+ - `files.sweep()` calls the store's `sweep` with the library's clock and returns how many documents
312
+ it removed: 0 when the store has no `sweep`. Run it on a schedule. The built-in stores also remove
313
+ an expired document when they are asked for it.
314
+ - `files.delete(id, { owner })` removes a document at once, with its index and its original. It
315
+ returns true when the document was there, and false when it was missing, had expired, or belongs to
316
+ another owner. Every server that shares the store sees the delete from its next call, since every
317
+ use asks the store first.
318
+ - A delete or an expiry does not reach what your application kept. Stored tool rounds hold
319
+ excerpts of the files (up to `toolResultCharacters` a result) and outlive both: your rules for
320
+ keeping and deleting data must cover them ([Conversations](./conversations.md)). What the model
321
+ provider keeps is in [Security](../security.md).
322
+
323
+ A chat that lives longer than `ttlMs` loses its documents, and its next question throws
324
+ `DocumentsNotFoundError`. To keep documents as long as their chat:
325
+
326
+ - Set a `ttlMs` longer than your chats live.
327
+ - Or set `ttlMs: Infinity`, and delete the documents yourself: with their chat (`deleteChat` above),
328
+ or in a job of your own after a time without use. Then a document whose ID your application never
329
+ recorded (an upload whose ID was never sent back, a server that stopped between ingest and saving
330
+ the session) stays for good: the library cannot find it. Keep the owner where you can query it,
331
+ as the [example store](#example-object-storage-and-a-database) does, or keep a finite `ttlMs`.
332
+ - Or, in a store of your own, write a later `expiresAt` into the metadata of a document whose chat
333
+ is in use. The library reads the date from `getMeta` before every use. Keep the format of
334
+ `toISOString()`. In the example store below, change `meta.expiresAt` and the record's own
335
+ `expiresAt` together: `sweep` and a TTL index read the second.
336
+
337
+ ## Keeping the uploaded files
338
+
339
+ By default a store keeps only the text of a document. `keepOriginals` also keeps the uploaded file:
340
+
341
+ | Option | Default | What it does |
342
+ |---|---|---|
343
+ | `keepOriginals` | `[]` | Formats whose uploaded file is kept next to its text, for example `["pdf"]`. |
344
+
345
+ ```ts
346
+ import type { ServerResponse } from "node:http";
347
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
348
+
349
+ export const files = createLargeFiles({
350
+ store: new FileDocumentStore(process.env.DOCUMENTS_DIR!),
351
+ keepOriginals: ["pdf"], // so that view_pages can show the model the pages of a PDF
352
+ });
353
+
354
+ /** A file name for `filename*` (RFC 8187), which does not allow ' ( ) *: encodeURIComponent leaves them. */
355
+ const encodeFileName = (name: string) =>
356
+ encodeURIComponent(name).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
357
+
358
+ /** Sends a kept upload back to its owner, or a 404. */
359
+ export async function sendOriginal(response: ServerResponse, id: string, owner: string): Promise<void> {
360
+ const meta = await files.getMeta(id, { owner });
361
+ const original = meta && await files.getOriginal(id, { owner });
362
+ if (!meta || !original) {
363
+ response.statusCode = 404;
364
+ response.end();
365
+ return;
366
+ }
367
+ // meta.mimeType is what the client declared at upload: do not serve the file as that.
368
+ response.setHeader("Content-Type", meta.format === "pdf" ? "application/pdf" : "application/octet-stream");
369
+ response.setHeader("Content-Disposition", `attachment; filename*=UTF-8''${encodeFileName(meta.name)}`);
370
+ response.setHeader("X-Content-Type-Options", "nosniff");
371
+ response.end(original);
372
+ }
373
+ ```
374
+
375
+ - It is off by default because it costs space: a kept file is as large as the upload, up to
376
+ `maxUploadBytes` (100 MB by default), and stays until the document expires or is deleted.
377
+ - A kept original is what `view_pages` shows the model, and what lets a scanned PDF be accepted.
378
+ Both are in [PDFs](./pdfs.md).
379
+ - The store needs `putOriginal` to keep a file and `getOriginal` to give it back. The built-in stores
380
+ have both. A store without `putOriginal` keeps nothing, whatever `keepOriginals` says.
381
+ - `meta.originalKept` is true when the file of a document is kept. `files.getOriginal(id, { owner })`
382
+ returns it, under the same owner rule as everything else. Treat the bytes as read-only: they may be
383
+ the store's own copy.
384
+ - Documents ingested before you turned it on have no original. Upload them again to get one.
385
+
386
+ ## Writing a store of your own
387
+
388
+ A store of your own implements `DocumentStore`: four methods are required, six are optional. The
389
+ library calls them. Your application calls them only to test the store, or to sweep a store that no
390
+ library uses.
391
+
392
+ ### The methods
393
+
394
+ | Method | Required | When the library calls it | What it must do |
395
+ |---|---|---|---|
396
+ | `put(document)` | Yes | `ingest`, last, after `putOriginal` and `putIndex`. | Keep `document.meta` whole, as one object, and `document.text`. Keep the text exactly, as UTF-8: `readTextRange` offsets point into those bytes. Let the document appear only once all of it is written. |
397
+ | `getMeta(id)` | Yes | Before every use of a document: `getMeta`, `getOriginal`, `delete`, `prepare` (once a document), and every tool call that reads one. | Return the metadata, or undefined when there is no such document. Keep it cheap: one look-up by key, without reading the text. |
398
+ | `get(id)` | Yes | To load a document whole: one whose text is at most `wholeDocumentBytes`, or any document when the store has no `readTextRange`. Once a library while the document stays in the cache. | Return `{ meta, text }` with the text exactly as `put` got it, or undefined. |
399
+ | `delete(id)` | Yes | `files.delete`, after the owner check. And `ingest`, to clean up after a write that failed. | Remove the metadata first, then the text, the index and the original. Return true when the document was there. Cope with a document that was only partly written. |
400
+ | `sweep(now?)` | No | `files.sweep()`, with the library's clock. | Remove the documents whose `expiresAt` is at or before `now`, with all their parts. Return how many. |
401
+ | `putOriginal(id, bytes)` | No | `ingest`, first, when `keepOriginals` lists the format. | Keep the bytes as they are now: the caller may reuse its buffer afterwards. |
402
+ | `getOriginal(id)` | No | `files.getOriginal` and `view_pages`, for a document whose `meta.originalKept` is true. | Return the bytes, or undefined. |
403
+ | `readTextRange(id, start, end)` | No | To read a document larger than `wholeDocumentBytes`, and to build its index. Only after `getMeta` found the document. | Return the bytes of the text from `start` (inclusive) to `end` (exclusive). See [Reading by range](#reading-by-range). |
404
+ | `putIndex(id, index)` | No | `ingest`, after `putOriginal` and before `put`, for every document. Again when a document read by range has no index, or one that does not match its text. | Keep the bytes. |
405
+ | `getIndex(id)` | No | When a document read by range is opened. | Return the bytes `putIndex` kept, or undefined. A damaged index is noticed and built again. |
406
+
407
+ The library checks `expiresAt` itself, with its own clock, before every use. Your `getMeta` and
408
+ `get` may return a document that has expired; your `sweep` must remove it.
409
+
410
+ Keep every field of `meta`, including those your store does not know. Later versions add optional
411
+ fields: 0.4.1 added `jsonBytes`, and 0.6.0 `encoding` and `replacedCharacters`, which say how a
412
+ text file that was not valid UTF-8 was read ([PDFs and other formats](./pdfs.md#text-encodings)).
413
+ A store that checks `meta` against a fixed list of fields (a `$jsonSchema` with
414
+ `additionalProperties: false`, a Mongoose schema in strict mode that throws) refuses the ingest of
415
+ every file that has them: a text file not in UTF-8, a UTF-8 log cut at a byte count, an ASCII log
416
+ with a stray byte. `createDocumentHandlers` then answers 500 "Upload failed.". A store that keeps
417
+ fixed columns and drops the others keeps the text, read right, but the model is no longer told how
418
+ the file was read. [The example below](#example-object-storage-and-a-database) stores `meta` whole.
419
+
420
+ What a missing optional method changes:
421
+
422
+ | Without | What happens |
423
+ |---|---|
424
+ | `sweep` | `files.sweep()` returns 0. Expired documents stay in storage until you remove them, although they are never served. |
425
+ | `putOriginal` | No original is kept, whatever `keepOriginals` says, and `meta.originalKept` is never set. No `view_pages`, and a PDF without text (a scan) is refused. |
426
+ | `getOriginal` | `files.getOriginal` returns undefined, and `view_pages` is never offered. |
427
+ | `readTextRange` | Every document is loaded whole with `get`, whatever its size, so memory grows with the size of the files in use and the number of users. `wholeDocumentBytes`, `scanChunkBytes` and `maxConcurrentScans` change nothing. |
428
+ | `putIndex` and `getIndex` | With `readTextRange` only: the index of a large document is built by reading its whole text once, 4 MB at a time, each time the document is opened, that is, each time it is not in the cache. |
429
+
430
+ ### Reading by range
431
+
432
+ `readTextRange(id, start, end)` is what lets a server answer questions about a 100 MB log without
433
+ holding it in memory. A tool call reads the lines it shows, and a search reads the text a piece at a
434
+ time ([the cache](#the-cache) has the sizes). The rules:
435
+
436
+ - `start` and `end` are UTF-8 byte offsets into the text exactly as `put` got it. The index is built
437
+ from those bytes at ingest, so do not re-encode the text, add a byte-order mark or change line
438
+ endings.
439
+ - Return every byte asked for, unless the text ends first. A read that comes back short in the
440
+ middle of the text is taken for a text that does not match its index: that call answers "The
441
+ stored text of report.log did not match its index. Try the call again.", and the index is built
442
+ again.
443
+ - Return fewer bytes at the end of the text, and an empty array when `start` is at or past its end.
444
+ That happens: the index is built by reading 4 MB at a time until a read comes back short, so a
445
+ text whose size is a multiple of 4 MB ends with a read that starts at its end.
446
+ - Return undefined when the document is gone. The call then answers "doc_… is no longer available on
447
+ the server. Ask the user to attach the file again."
448
+
449
+ How that maps to common storage:
450
+
451
+ - Object storage over HTTP (S3, Cloud Storage, Azure Blob Storage): send `Range:
452
+ bytes=${start}-${end - 1}`, since the last byte of an HTTP range is included. A range that runs past
453
+ the end gives what there is. One that starts at or past the end is answered 416 (Range Not
454
+ Satisfiable): return an empty array then.
455
+ - Redis: `GETRANGE key start end-1`, whose end is included too. It answers an empty string for a
456
+ missing key as well, so tell the two apart before you return an empty array.
457
+ - A file on a volume: read at an offset, as `FileDocumentStore` does.
458
+
459
+ ### Errors
460
+
461
+ Return undefined only when the document is not there. Throw for everything else: a database that is
462
+ down, a timeout, a refused permission. A store that returns undefined for a failure tells the library
463
+ the document is gone, and the user is asked to upload it again.
464
+
465
+ What the library does with what you throw depends on the call:
466
+
467
+ - **Reads** (`get`, `getMeta`, `getOriginal`, `readTextRange`): whatever you throw is passed on as a
468
+ `DocumentStoreError`. Its message is "The document store could not be read (EIO). Try again.", with
469
+ the code in parentheses only when your error has a string `code`. Its `code` and `syscall` are
470
+ those of your error, when they are strings, as a Node system error has them. Its `cause` is your
471
+ error: log that one. The message names no path or host, so it can be shown to a user or a model.
472
+ `prepare`, `askWithFiles` and `files.getMeta` throw it; a tool call answers the model with its
473
+ message, and the model can try again. A `DocumentStoreError` you throw yourself
474
+ (`new DocumentStoreError(cause)`, which takes only the cause) is passed on as it is; you never need
475
+ to. What to show the user is in [Errors and reliability](./errors-and-reliability.md).
476
+ - **`getIndex`**: an error is not passed on. The index is built from the text instead.
477
+ - **Writes at ingest** (`putOriginal`, `putIndex`, `put`): the library calls `delete(id)` to remove
478
+ what was written, ignores any error of that, and throws your error as it came. Through the `upload`
479
+ handler of `createDocumentHandlers`, an error with a `status` (or `statusCode`) from 400 to 599 is
480
+ answered with that status and its message (a 413 with "The file is larger than the … upload
481
+ limit.", and an empty message with "Upload failed."). A Node system error (a string `code` and
482
+ `syscall`) is answered 500 "Upload failed (CODE).". Any other error, or a thrown value that is not
483
+ an `Error`, is answered 500 "Upload failed.", without its message, which may name a database host.
484
+ The handlers log nothing: log your error in the store before you throw. Two paths cannot tell
485
+ your error from a file that cannot be read, and answer it 422 with its message, host and all: an
486
+ `ingest` of your own that throws a new error in place of yours, and a route of your own. See the
487
+ [node reference](../reference/node.md#uploadrequest-response). Give your write errors a status and
488
+ a message of your own, as the example below does: every path keeps that status.
489
+ - **`delete` and `sweep`**: your error comes out of `files.delete` and `files.sweep` as it came. The
490
+ DELETE handler answers it 500 without its message, unless it has a status.
491
+ - **`putIndex` on a later read**: an error is ignored. The index is used from memory, and built again
492
+ the next time.
493
+
494
+ ### Concurrency and several servers
495
+
496
+ - Every method may run many times at once, for the same document too. Many users ask at once, the
497
+ tool calls of one turn run together, and a search reads the next piece of a text while it searches
498
+ the current one.
499
+ - In one library, calls that open the same document at the same time share one opening: one `get`,
500
+ or one `getIndex`.
501
+ - A document is written once: its ID is new at every ingest. Only `putIndex` writes again, later, for
502
+ a document whose index was missing or did not match its text. Several servers may do that at once,
503
+ with the same bytes: let the last write win.
504
+ - Make the metadata the point where a document exists. Write it last, in `put`, after the text, and
505
+ remove it first in `delete`. A server that finds the metadata must be able to read all of the text.
506
+ `FileDocumentStore` gets this on a shared volume by writing under a temporary name and renaming.
507
+ - A document deleted by another server between `getMeta` and a read is answered as gone: return
508
+ undefined from that read.
509
+
510
+ ### Example: object storage and a database
511
+
512
+ This store keeps the metadata in a MongoDB collection and the text, the index and the original in
513
+ object storage. The object storage calls are behind a small interface of your own, `Blobs`, so the
514
+ store works over S3, Cloud Storage, Azure Blob Storage or a volume: write those four calls with your
515
+ SDK, following [Reading by range](#reading-by-range).
516
+
517
+ ```ts
518
+ // blob-document-store.ts
519
+ import type { Collection } from "mongodb";
520
+ import { DOCUMENT_ID_PATTERN, type DocumentMeta, type DocumentStore, type StoredDocument } from "llm-large-files";
521
+
522
+ /** The object storage calls the store needs. Write them over S3, Cloud Storage, Azure Blob Storage or a volume. */
523
+ export interface Blobs {
524
+ /** Writes the whole object, replacing any object under that key. */
525
+ write(key: string, bytes: Uint8Array): Promise<void>;
526
+ /** The whole object, or undefined when there is no such object. Throws on any other failure. */
527
+ read(key: string): Promise<Uint8Array | undefined>;
528
+ /**
529
+ * Bytes `start` (inclusive) to `end` (exclusive): fewer at the end of the object, an empty array
530
+ * when `start` is at or past its end, and undefined when there is no such object.
531
+ */
532
+ readRange(key: string, start: number, end: number): Promise<Uint8Array | undefined>;
533
+ /** Removes the object. No error when there is none. */
534
+ remove(key: string): Promise<void>;
535
+ }
536
+
537
+ /** One record a document: the metadata, and two fields copied out of it to query by. */
538
+ export type DocumentRecord = {
539
+ _id: string;
540
+ meta: DocumentMeta;
541
+ owner: string | null;
542
+ expiresAt: Date;
543
+ };
544
+
545
+ /** A write that failed: a 503 from createDocumentHandlers, with a message that names no host. */
546
+ function notStored(cause: unknown): Error {
547
+ console.error("document store write failed", cause); // the handlers log nothing
548
+ return Object.assign(new Error("The file could not be stored. Try again.", { cause }), { status: 503 });
549
+ }
550
+
551
+ export class BlobDocumentStore implements DocumentStore {
552
+ constructor(
553
+ private readonly blobs: Blobs,
554
+ private readonly records: Collection<DocumentRecord>,
555
+ private readonly prefix = "llm-large-files",
556
+ ) {}
557
+
558
+ /** Only a document ID becomes part of a key, as in the built-in stores. */
559
+ private key(id: string, kind: "txt" | "idx" | "bin"): string {
560
+ if (!DOCUMENT_ID_PATTERN.test(id)) throw new Error("Invalid document ID.");
561
+ return `${this.prefix}/${id}.${kind}`;
562
+ }
563
+
564
+ /** Called last at ingest. The text first, the record last: a document exists once its record does. */
565
+ async put({ meta, text }: StoredDocument): Promise<void> {
566
+ try {
567
+ await this.blobs.write(this.key(meta.id, "txt"), new TextEncoder().encode(text));
568
+ await this.records.insertOne({ _id: meta.id, meta, owner: meta.owner ?? null, expiresAt: new Date(meta.expiresAt) });
569
+ } catch (error) {
570
+ throw notStored(error);
571
+ }
572
+ }
573
+
574
+ /** Called before every use of a document: one look-up by key. */
575
+ async getMeta(id: string): Promise<DocumentMeta | undefined> {
576
+ return (await this.records.findOne({ _id: id }))?.meta;
577
+ }
578
+
579
+ async get(id: string): Promise<StoredDocument | undefined> {
580
+ const meta = await this.getMeta(id);
581
+ const bytes = meta && await this.blobs.read(this.key(id, "txt"));
582
+ return meta && bytes ? { meta, text: new TextDecoder().decode(bytes) } : undefined;
583
+ }
584
+
585
+ /** UTF-8 bytes of the text exactly as `put` wrote it. Called only after getMeta found the document. */
586
+ async readTextRange(id: string, start: number, end: number): Promise<Uint8Array | undefined> {
587
+ if (end <= start) return new Uint8Array(0); // never send an empty range to storage
588
+ return this.blobs.readRange(this.key(id, "txt"), start, end);
589
+ }
590
+
591
+ async putIndex(id: string, index: Uint8Array): Promise<void> {
592
+ try {
593
+ await this.blobs.write(this.key(id, "idx"), index);
594
+ } catch (error) {
595
+ throw notStored(error);
596
+ }
597
+ }
598
+
599
+ async getIndex(id: string): Promise<Uint8Array | undefined> {
600
+ return this.blobs.read(this.key(id, "idx"));
601
+ }
602
+
603
+ async putOriginal(id: string, bytes: Uint8Array): Promise<void> {
604
+ try {
605
+ await this.blobs.write(this.key(id, "bin"), bytes);
606
+ } catch (error) {
607
+ throw notStored(error);
608
+ }
609
+ }
610
+
611
+ async getOriginal(id: string): Promise<Uint8Array | undefined> {
612
+ return await this.getMeta(id) ? this.blobs.read(this.key(id, "bin")) : undefined;
613
+ }
614
+
615
+ /** The record first: if removing it fails, nothing else is touched and the document stays whole. */
616
+ async delete(id: string): Promise<boolean> {
617
+ if (!DOCUMENT_ID_PATTERN.test(id)) return false;
618
+ const { deletedCount } = await this.records.deleteOne({ _id: id });
619
+ // Also what a failed ingest left behind: an original or an index without a record.
620
+ await Promise.all((["txt", "idx", "bin"] as const).map((kind) => this.blobs.remove(this.key(id, kind))));
621
+ return deletedCount > 0;
622
+ }
623
+
624
+ async sweep(now = new Date()): Promise<number> {
625
+ const expired = await this.records.find({ expiresAt: { $lte: now } }, { projection: { _id: 1 } }).toArray();
626
+ let removed = 0;
627
+ for (const { _id } of expired) {
628
+ // One that cannot be removed now waits for the next sweep, and does not stop this one.
629
+ if (await this.delete(_id).catch(() => false)) removed++;
630
+ }
631
+ return removed;
632
+ }
633
+ }
634
+ ```
635
+
636
+ And the library over it:
637
+
638
+ ```ts
639
+ // large-files.ts
640
+ import { MongoClient } from "mongodb";
641
+ import { createLargeFiles } from "llm-large-files";
642
+ import { BlobDocumentStore, type DocumentRecord } from "./blob-document-store.js";
643
+ import { blobs } from "./blobs.js"; // your Blobs over S3, Cloud Storage or a volume
644
+
645
+ const mongo = new MongoClient(process.env.MONGODB_URI!);
646
+ const records = mongo.db("chat").collection<DocumentRecord>("documents");
647
+
648
+ export const files = createLargeFiles({
649
+ store: new BlobDocumentStore(blobs, records),
650
+ keepOriginals: ["pdf"],
651
+ });
652
+ ```
653
+
654
+ - Reads let their errors through: the library turns them into a `DocumentStoreError`. Writes log
655
+ theirs, then turn them into an error with status 503 and a message of their own, so an upload that
656
+ meets a database that is down is answered 503 "The file could not be stored. Try again.", not 500
657
+ "Upload failed.".
658
+ - `delete` removes the record first. If removing an object fails after that, the document is gone
659
+ and the object stays behind. A lifecycle rule on the bucket that removes objects under the prefix
660
+ some time after `ttlMs` cleans those up, when `ttlMs` is finite.
661
+ - Index the collection on `expiresAt` for the sweep, and on `owner` to find a user's documents:
662
+ `records.find({ owner: userId })` gives the IDs to pass to `files.delete(id, { owner: userId })`.
663
+ - A MongoDB TTL index on `expiresAt` (`expireAfterSeconds: 0`) removes the records without a sweep,
664
+ but not the objects. It needs a lifecycle rule on the bucket as well.
665
+
666
+ ### Checking your store
667
+
668
+ Before you trust a store with users' files, check these with the library over it:
669
+
670
+ - A file ingested, then `prepare` and a `search_document` call give the same results as with
671
+ `MemoryDocumentStore`. Do it once more with `wholeDocumentBytes: 0`, which reads every document by
672
+ range.
673
+ - With the database stopped, `files.getMeta(id)` rejects with a `DocumentStoreError` instead of
674
+ giving undefined, and a tool call answers "The document store could not be read. Try again.",
675
+ with a code in parentheses when your error has one.
676
+ - A text file that is not UTF-8, such as a CSV saved by Excel in windows-1255, is ingested, and
677
+ `files.getMeta(id)` gives back its `encoding` (and `replacedCharacters`, for a UTF-8 log cut at a
678
+ byte count): your store keeps fields it does not know.
679
+ - With a write that fails, `files.ingest` throws, and leaves no record and no object behind.
680
+ - `files.delete` removes every part. `getMeta` then gives undefined, and a second delete gives false.
681
+ - With a clock past `expiresAt` (the `now` option of `createLargeFiles`), `files.sweep()` removes
682
+ the document, every part of it, and counts it.
683
+ - `readTextRange(id, size, size + 10)` gives an empty array, where `size` is `meta.textBytes`.
684
+ - With `keepOriginals`, `files.getOriginal` gives the uploaded bytes, byte for byte.
685
+
686
+ ## The cache
687
+
688
+ Each library keeps documents ready in memory between tool calls. A document loaded whole is read
689
+ from the store once, however many tool calls use it. For a document read by range, it keeps the
690
+ line index and, for searches, decoded pieces of the text, and each read of lines asks the store for
691
+ just those lines.
692
+
693
+ | Option | Default | What it does |
694
+ |---|---|---|
695
+ | `cacheBytes` | `DEFAULT_CACHE_BYTES`: 256 MB | The most memory the kept documents may take, decoded pieces of large documents included. The least recently used go first. A document larger than this is read again for each call. `0` keeps none. |
696
+ | `cacheSize` | No cap | Also caps the number of documents kept. The pieces of a document read by range do not count. |
697
+ | `wholeDocumentBytes` | `DEFAULT_WHOLE_DOCUMENT_BYTES`: 2 MB | A document whose text is at most this many bytes is loaded whole. A larger one is read by range, when the store has `readTextRange`. `Infinity` loads every document whole; `0` reads every one by range. |
698
+ | `scanChunkBytes` | 1 MB | Reading by range: about this many bytes of text are read and searched at a time. |
699
+ | `maxConcurrentScans` | 4 | Reading by range: how many scans of whole documents (searches, counting the parts of a file) run at once in this library. The others wait their turn. |
700
+
701
+ - The cache never decides whether a document exists. Every use asks the store first (`getMeta`), so
702
+ a document deleted or expired on another server is never served from memory here. A kept copy is
703
+ used only while the store describes the same text (the same `createdAt`, size, characters and
704
+ lines), so a store restored from a backup is read again.
705
+ - A document loaded whole takes, once searched, about twice its size in memory when its text is all
706
+ ASCII, and four bytes a character otherwise: the text and a lowercased copy.
707
+ - A document read by range keeps its line index in memory, about 8 bytes a line, and, within
708
+ `cacheBytes`, the decoded pieces of its text, so the next search reads nothing. A document whose
709
+ decoded text would take more than a quarter of `cacheBytes` never has its pieces kept: one search
710
+ of it would push everything else out.
711
+ - A document read by range is read whole only when the plan sends its whole text in the prompt.
712
+ - Searches of one document read by range that wait for a turn together share one pass over its
713
+ text: it is read, decoded and lowercased once for all of them.
714
+
715
+ The cache belongs to a library, which is to say, in most applications, to a process. Memory per
716
+ server and what each server keeps for itself are in [Deployment](./deployment.md).
717
+
718
+ ## Related pages
719
+
720
+ - [Web app](./web-app.md): upload routes, `getOwner`, and answers streamed to the browser.
721
+ - [Conversations](./conversations.md): storing a chat, its tool rounds, and its documents across
722
+ questions.
723
+ - [Deployment](./deployment.md): several servers on one store, memory, the sweep, upgrades.
724
+ - [Errors and reliability](./errors-and-reliability.md): `DocumentStoreError`,
725
+ `DocumentsNotFoundError`, and what to show the user.
726
+ - [PDFs](./pdfs.md): `view_pages` and scanned PDFs, which need kept originals.
727
+ - [Security](../security.md): ownership, retention and what the files on disk hold.
728
+ - [How it works](../how-it-works.md): the plan, the tools and how a document is read.
729
+ - [The library reference](../reference/library.md): `createLargeFiles`, `LargeFilesOptions`,
730
+ `DocumentStore`, `MemoryDocumentStore`, `FileDocumentStore`, `DocumentStoreError`,
731
+ `NEVER_EXPIRES` and the rest.