llm-large-files 0.8.2 → 0.9.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 (201) hide show
  1. package/CHANGELOG.md +535 -0
  2. package/README.md +9 -10
  3. package/dist/access.d.ts +86 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +131 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/ask.d.ts +45 -1
  8. package/dist/ask.d.ts.map +1 -1
  9. package/dist/ask.js +181 -20
  10. package/dist/ask.js.map +1 -1
  11. package/dist/cache.d.ts +12 -3
  12. package/dist/cache.d.ts.map +1 -1
  13. package/dist/cache.js +18 -5
  14. package/dist/cache.js.map +1 -1
  15. package/dist/encoding.js +5 -3
  16. package/dist/encoding.js.map +1 -1
  17. package/dist/error-info.d.ts +57 -0
  18. package/dist/error-info.d.ts.map +1 -0
  19. package/dist/error-info.js +217 -0
  20. package/dist/error-info.js.map +1 -0
  21. package/dist/errors.d.ts +72 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +102 -15
  24. package/dist/errors.js.map +1 -1
  25. package/dist/events.d.ts +35 -9
  26. package/dist/events.d.ts.map +1 -1
  27. package/dist/events.js +42 -11
  28. package/dist/events.js.map +1 -1
  29. package/dist/evidence.d.ts +4 -2
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +14 -3
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +32 -8
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +46 -35
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts +19 -3
  38. package/dist/gemini/adapter.d.ts.map +1 -1
  39. package/dist/gemini/adapter.js +84 -12
  40. package/dist/gemini/adapter.js.map +1 -1
  41. package/dist/gemini/chat.d.ts +18 -6
  42. package/dist/gemini/chat.d.ts.map +1 -1
  43. package/dist/gemini/chat.js +2 -0
  44. package/dist/gemini/chat.js.map +1 -1
  45. package/dist/gemini/index.d.ts +1 -1
  46. package/dist/gemini/index.d.ts.map +1 -1
  47. package/dist/index.d.ts +9 -6
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/ingest.d.ts +70 -0
  52. package/dist/ingest.d.ts.map +1 -0
  53. package/dist/ingest.js +868 -0
  54. package/dist/ingest.js.map +1 -0
  55. package/dist/library.d.ts +169 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +324 -591
  58. package/dist/library.js.map +1 -1
  59. package/dist/map-reduce.js +3 -3
  60. package/dist/map-reduce.js.map +1 -1
  61. package/dist/model.d.ts +43 -2
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +63 -3
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts +226 -14
  66. package/dist/node/handlers.d.ts.map +1 -1
  67. package/dist/node/handlers.js +423 -181
  68. package/dist/node/handlers.js.map +1 -1
  69. package/dist/node/index.d.ts +3 -2
  70. package/dist/node/index.d.ts.map +1 -1
  71. package/dist/node/index.js +2 -1
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/node/ingest-child.d.ts +7 -1
  74. package/dist/node/ingest-child.d.ts.map +1 -1
  75. package/dist/node/ingest-child.js +18 -3
  76. package/dist/node/ingest-child.js.map +1 -1
  77. package/dist/node/isolated.d.ts +3 -1
  78. package/dist/node/isolated.d.ts.map +1 -1
  79. package/dist/node/isolated.js +11 -4
  80. package/dist/node/isolated.js.map +1 -1
  81. package/dist/node/originals.d.ts +19 -0
  82. package/dist/node/originals.d.ts.map +1 -0
  83. package/dist/node/originals.js +82 -0
  84. package/dist/node/originals.js.map +1 -0
  85. package/dist/node/spool.d.ts +102 -0
  86. package/dist/node/spool.d.ts.map +1 -0
  87. package/dist/node/spool.js +365 -0
  88. package/dist/node/spool.js.map +1 -0
  89. package/dist/node/sse.d.ts +4 -3
  90. package/dist/node/sse.d.ts.map +1 -1
  91. package/dist/node/sse.js +7 -6
  92. package/dist/node/sse.js.map +1 -1
  93. package/dist/pdf-layout.d.ts.map +1 -1
  94. package/dist/pdf-layout.js +71 -12
  95. package/dist/pdf-layout.js.map +1 -1
  96. package/dist/ranged.d.ts +15 -11
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +42 -11
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/retry.d.ts +3 -1
  101. package/dist/retry.d.ts.map +1 -1
  102. package/dist/retry.js +6 -2
  103. package/dist/retry.js.map +1 -1
  104. package/dist/scope.d.ts +25 -0
  105. package/dist/scope.d.ts.map +1 -0
  106. package/dist/scope.js +60 -0
  107. package/dist/scope.js.map +1 -0
  108. package/dist/source.d.ts +60 -0
  109. package/dist/source.d.ts.map +1 -0
  110. package/dist/source.js +170 -0
  111. package/dist/source.js.map +1 -0
  112. package/dist/stores.d.ts +120 -31
  113. package/dist/stores.d.ts.map +1 -1
  114. package/dist/stores.js +582 -139
  115. package/dist/stores.js.map +1 -1
  116. package/dist/testing/fake-fetch.d.ts +31 -0
  117. package/dist/testing/fake-fetch.d.ts.map +1 -0
  118. package/dist/testing/fake-fetch.js +66 -0
  119. package/dist/testing/fake-fetch.js.map +1 -0
  120. package/dist/testing/fake-model.d.ts +38 -0
  121. package/dist/testing/fake-model.d.ts.map +1 -0
  122. package/dist/testing/fake-model.js +62 -0
  123. package/dist/testing/fake-model.js.map +1 -0
  124. package/dist/testing/index.d.ts +7 -0
  125. package/dist/testing/index.d.ts.map +1 -0
  126. package/dist/testing/index.js +9 -0
  127. package/dist/testing/index.js.map +1 -0
  128. package/dist/testing/store-checks.d.ts +72 -0
  129. package/dist/testing/store-checks.d.ts.map +1 -0
  130. package/dist/testing/store-checks.js +619 -0
  131. package/dist/testing/store-checks.js.map +1 -0
  132. package/dist/tools.d.ts +25 -0
  133. package/dist/tools.d.ts.map +1 -1
  134. package/dist/tools.js +135 -13
  135. package/dist/tools.js.map +1 -1
  136. package/dist/types.d.ts +116 -13
  137. package/dist/types.d.ts.map +1 -1
  138. package/docs/README.md +17 -8
  139. package/docs/getting-started.md +18 -13
  140. package/docs/guides/anthropic.md +12 -8
  141. package/docs/guides/conversations.md +112 -47
  142. package/docs/guides/costs-and-limits.md +16 -7
  143. package/docs/guides/deployment.md +284 -83
  144. package/docs/guides/errors-and-reliability.md +161 -23
  145. package/docs/guides/own-adapter-and-loop.md +27 -10
  146. package/docs/guides/pdfs.md +123 -29
  147. package/docs/guides/storage.md +633 -145
  148. package/docs/guides/testing.md +78 -129
  149. package/docs/guides/vertex-and-gemini.md +10 -7
  150. package/docs/guides/web-app.md +312 -78
  151. package/docs/how-it-works.md +35 -8
  152. package/docs/measurements.md +43 -8
  153. package/docs/publishing.md +112 -36
  154. package/docs/reference/ask.md +154 -13
  155. package/docs/reference/errors-and-retries.md +166 -14
  156. package/docs/reference/events.md +53 -20
  157. package/docs/reference/gemini.md +70 -21
  158. package/docs/reference/library.md +706 -165
  159. package/docs/reference/node.md +624 -110
  160. package/docs/reference/testing.md +311 -0
  161. package/docs/reference/tools.md +15 -5
  162. package/docs/security.md +304 -67
  163. package/docs/troubleshooting.md +144 -65
  164. package/docs/upgrading-0.9.md +890 -0
  165. package/package.json +12 -3
  166. package/src/access.ts +144 -0
  167. package/src/ask.ts +230 -19
  168. package/src/cache.ts +20 -5
  169. package/src/encoding.ts +6 -4
  170. package/src/error-info.ts +255 -0
  171. package/src/errors.ts +129 -15
  172. package/src/events.ts +86 -21
  173. package/src/evidence.ts +14 -3
  174. package/src/extract.ts +50 -33
  175. package/src/gemini/adapter.ts +97 -11
  176. package/src/gemini/chat.ts +20 -6
  177. package/src/gemini/index.ts +1 -1
  178. package/src/index.ts +9 -6
  179. package/src/ingest.ts +927 -0
  180. package/src/library.ts +467 -601
  181. package/src/map-reduce.ts +3 -3
  182. package/src/model.ts +69 -5
  183. package/src/node/handlers.ts +630 -183
  184. package/src/node/index.ts +13 -2
  185. package/src/node/ingest-child.ts +23 -5
  186. package/src/node/isolated.ts +11 -4
  187. package/src/node/originals.ts +78 -0
  188. package/src/node/spool.ts +365 -0
  189. package/src/node/sse.ts +7 -6
  190. package/src/pdf-layout.ts +69 -11
  191. package/src/ranged.ts +34 -13
  192. package/src/retry.ts +6 -2
  193. package/src/scope.ts +63 -0
  194. package/src/source.ts +178 -0
  195. package/src/stores.ts +635 -140
  196. package/src/testing/fake-fetch.ts +80 -0
  197. package/src/testing/fake-model.ts +78 -0
  198. package/src/testing/index.ts +11 -0
  199. package/src/testing/store-checks.ts +660 -0
  200. package/src/tools.ts +150 -14
  201. package/src/types.ts +106 -13
@@ -32,8 +32,9 @@ sees them:
32
32
  read whose parts all failed) returns its error to the model, which tries another way. Nothing is
33
33
  thrown. See [Failures inside tools](#failures-inside-tools).
34
34
 
35
- What is left for you: catch what the question throws, show your own words for it, keep what a
36
- failed question found, check `answered`, and set an overall deadline.
35
+ What is left for you: catch what the question throws, show your own words for it (one switch over
36
+ [`errorInfoOf`](#your-users-words-errorinfoof) does it), keep what a failed question found, check
37
+ `answered`, and set an overall deadline.
37
38
 
38
39
  ## What a question can throw
39
40
 
@@ -41,7 +42,7 @@ failed question found, check `answered`, and set an overall deadline.
41
42
 
42
43
  | Error | When | Fields to use | `partialResultOf` |
43
44
  |---|---|---|---|
44
- | `DocumentsNotFoundError` | A document ID was never uploaded, has expired, was deleted, or belongs to another `owner`. Thrown before any model request. | `ids`: the IDs that are missing. | No |
45
+ | `DocumentsNotFoundError` | A document ID was never uploaded, has expired, was deleted, or belongs to another `owner` or scope. Thrown before any model request, unless `onMissingDocuments` says to answer without it or brings it back (new in 0.9.0, [below](#documents-that-are-gone)). | `ids`: the IDs that are missing. | No |
45
46
  | `DocumentStoreError` | The store could not be read while the question planned its documents: a volume that did not answer, a database that is down. The documents are not gone, and the same question may work a moment later. | `code` (`EIO`, `EMFILE`) and `syscall` when a system error is behind it; `cause`, the error that was caught. | No |
46
47
  | `ModelRequestError`: a `GeminiRequestError`, `OpenAiRequestError` or `AnthropicRequestError` | A model request failed in a way that was not worth sending again, or still failed after the retries. A reply of HTTP 200 whose body is not JSON (a gateway's page in the model's place) is one too, of kind `invalid`, with status 200 and the `SyntaxError` as `cause`; it is not sent again. A reply of HTTP 200 whose body is empty is of kind `unreachable`, status 0, and is sent again first. | `kind`, `status` (0 when no answer came, or the reply stopped on its way), `retryAfterMs`, `limitTokens`, `requestedTokens`, `cause`. `OpenAiRequestError` adds `param` and `code`; `AnthropicRequestError` adds `type`. | Yes |
47
48
  | The reason of your `signal` | You stopped the question, or your deadline ran out. See [An overall deadline](#an-overall-deadline). | Test your signals, not the error. | Yes, for a reason that is an object |
@@ -78,12 +79,13 @@ Whose words each message is:
78
79
 
79
80
  Use `instanceof` for the classes, and `errorKindOf(error)` for the kind. `errorKindOf` reads the
80
81
  `kind` field of any error that has one, so it also works when two copies of the package are
81
- installed side by side, where `instanceof` fails. The four model error classes are all
82
- `ModelRequestError`.
82
+ installed side by side, where `instanceof` fails; so do the classes' own `is(value)` methods, new
83
+ in 0.9.0. The four model error classes are all `ModelRequestError`. Or let
84
+ [`errorInfoOf`](#your-users-words-errorinfoof) tell them apart for you (new in 0.9.0).
83
85
 
84
86
  | Export | Entry point |
85
87
  |---|---|
86
- | `ModelRequestError`, `errorKindOf`, `classifyModelError`, `DocumentsNotFoundError`, `DocumentStoreError`, `partialResultOf` | `llm-large-files` |
88
+ | `ModelRequestError`, `errorKindOf`, `classifyModelError`, `DocumentsNotFoundError`, `DocumentStoreError`, `partialResultOf`, `errorInfoOf` | `llm-large-files` |
87
89
  | `GeminiRequestError`, and `DocumentsNotFoundError` and `partialResultOf` again | `llm-large-files/gemini` |
88
90
  | `OpenAiRequestError` | `llm-large-files/openai` |
89
91
  | `AnthropicRequestError` | `llm-large-files/anthropic` |
@@ -341,7 +343,9 @@ How the client side cancels a streamed answer is in [Web app](./web-app.md).
341
343
  When the provider refuses a request as larger than the model takes (kind `context_overflow`), the
342
344
  loop does not give up at once. The same holds for a request larger than the tokens the provider
343
345
  lets through in a minute (OpenAI's and Groq's TPM, or a day's allowance): that allowance then
344
- stands for the window.
346
+ stands for the window. Since 0.9.0 the loop reads the kind as the events report it: an error
347
+ without a `kind` of its own that has a model's status (an adapter of your own, `httpError(413)`)
348
+ has the kind `classifyModelError` gives its status, message and `code`.
345
349
 
346
350
  1. It takes the provider's count and window for the rest of the question, replaces tool results
347
351
  with stand-ins (those of all but the last three tool rounds, then all but the last two, then all
@@ -608,8 +612,8 @@ written for the user and a `code` for your app, when it cannot take a file: it i
608
612
  (`"no_text"`), is a gzip or ZIP archive (`"compressed"`), is binary (`"not_text"`), is an Office
609
613
  file of before 2007 or with a password (`"legacy_office"`), needs an optional dependency that is not
610
614
  installed (`jszip` for DOCX, PPTX and XLSX, `unpdf` for PDF) or an `unpdf` that runs on this Node
611
- (`"missing_dependency"`: the setup of the server, not the file, as in "The unpdf installed cannot
612
- read PDF files on Node 20 (…). …"), or is a PDF without a text layer (see [PDFs](./pdfs.md)). Show
615
+ (`"missing_dependency"`: the setup of the server, not the file, as in "The unpdf installed would
616
+ stop the whole server at the first PDF file on Node 22, …"), or is a PDF without a text layer (see [PDFs](./pdfs.md)). Show
613
617
  its message, or words of your own for its `code`. Until 0.8.0 it was a plain `Error`, with the same
614
618
  message. A text file is never refused for its encoding: one that is
615
619
  not UTF-8 is read in the encoding it was saved in, or as UTF-8 with the characters that are not
@@ -624,30 +628,163 @@ A file the parser cannot read (a damaged DOCX, PPTX, XLSX or PDF) throws an `Ing
624
628
  `"unreadable"` with the parser's message (jszip's, or that of pdf.js's `InvalidPDFException`), and
625
629
  the parser's error as `cause`; an extractor of your own that throws an `Error` gets the same, with
626
630
  the code its message gives. Those messages are not written for users: show "This file could not
627
- be read." for the code `"unreadable"`. With `createIsolatedExtractors`, a file whose reader ran out
631
+ be read." for the code `"unreadable"`. Since 0.9.0 the upload handlers, `uploadAnswerOf` and
632
+ `errorInfoOf` do: "This file could not be read. It may be damaged, or not of the type its name
633
+ says.". With `createIsolatedExtractors`, a file whose reader ran out
628
634
  of memory or time is `"out_of_memory"` or `"timeout"`, readers that are all busy give `"busy"`,
629
635
  answered `503` with `Retry-After`, and a reader that could not start at all (a `childScript` that
630
636
  is not there) is not an `IngestError`, but an `Error` with `status` 500
631
637
  ([node reference](../reference/node.md#createisolatedextractorsoptions)).
632
638
 
633
- A store that fails while it writes throws its own error, as it came: its message may name a path or
634
- a host, so log it and show a general message. `createDocumentHandlers` answers a file it cannot take
635
- with 422 and the error's message, and a Node system error of the store (one with a `code` and a
636
- `syscall`) with 500 and only its code ("Upload failed (ENOSPC)."). Any other store error, one
637
- without a `status` (or `statusCode`) from 400 to 599, is answered 500 "Upload failed.", without its
638
- message, and so is a thrown value that is not an `Error`. The handlers log nothing: log the error in
639
- your store before you throw it. Two paths still answer a store's error 422 with its message, which
640
- may name a host: an `ingest` of your own that throws a new error in its place, as `ingestInProcess`
641
- in [Deployment](./deployment.md#uploads-and-ingest) does, and a route of your own, as in
642
- [Web app](./web-app.md#filesingest-and-its-errors). So a custom store should throw an error with a
643
- `status` and a message fit for the user (both are sent as they are): every path keeps that status.
644
- See [the node reference](../reference/node.md#uploadrequest-response).
639
+ A store that fails while it writes is a `DocumentStoreError` since 0.9.0: operation `"write"` in
640
+ `ingest` (code `"ETIMEDOUT"` for a write that did not end in time), `"delete"` in `files.delete`,
641
+ `"sweep"` in `files.sweep`. Its status is 503, its message ("The document could not be stored
642
+ (EIO). Try again.") names no path or host and can be shown, and the store's own error is `cause`:
643
+ log that one. Before 0.9.0 the store's error came out as it was. The `ingest.error` event of a
644
+ failed write says "The document could not be stored. Try again later.", with `name`
645
+ `"DocumentStoreError"` and `status` 503 (new in 0.9.0), and `errorInfoOf` reads it as the error.
646
+ `createDocumentHandlers` answers a
647
+ file it cannot take (an `IngestError`) with 422 and the error's message (fixed words for
648
+ `"unreadable"`), and a store that failed
649
+ with 503, `Retry-After: 5` and the `DocumentStoreError`'s message (it was a 500). Since 0.9.0 any
650
+ other error without a status is answered 500 "Upload failed.", without its message: a `LargeFiles`
651
+ of your own whose `ingest` throws a plain `Error` no longer sends its words, which may name a host,
652
+ as a 422 (S12). Throw `new IngestError(code, message)` for a file you refuse, as `ingestInProcess`
653
+ in [Deployment](./deployment.md#uploads-and-ingest) does. A route of your own answers the same way
654
+ with `uploadAnswerOf` from `llm-large-files/node` ([Web app](./web-app.md#filesingest-and-its-errors)).
655
+ The handlers log nothing: log `error.cause`. See
656
+ [the node reference](../reference/node.md#how-errors-are-answered).
645
657
 
646
658
  Every read of the store goes through the library: `prepare`, `getMeta`, `getOriginal`, the tools.
647
659
  What the store throws there becomes a `DocumentStoreError`, which does not mean the document is
648
660
  gone. A store's own `delete` and `sweep` pass on its error as it came. A document that is gone, or
649
661
  of another owner, is not an error of the store: `prepare` lists it in `missing`, and `askWithFiles`
650
- throws `DocumentsNotFoundError` for it. What a store must do is in [Storage](./storage.md).
662
+ throws `DocumentsNotFoundError` for it, unless `onMissingDocuments` says otherwise (below). What a
663
+ store must do is in [Storage](./storage.md).
664
+
665
+ ## Documents that are gone
666
+
667
+ A document expires `ttlMs` after its upload (72 hours by default), and a chat can outlive it. By
668
+ default the next question then fails whole, before any model request, with
669
+ `DocumentsNotFoundError`. New in 0.9.0, `onMissingDocuments` settles it in the question
670
+ ([missing documents](../reference/ask.md#missing-documents)):
671
+
672
+ | `onMissingDocuments` | What the question does |
673
+ |---|---|
674
+ | `"throw"` (the default) | Throws `DocumentsNotFoundError`, as before. |
675
+ | `"drop"` | Answers without them. One line of the system instruction tells the model how many files are no longer available. `result.missing` lists their IDs; take them off the chat, and tell the user. |
676
+ | A function | Gets the missing IDs, with the question's `owner`, `scope` and `signal`, and returns `"throw"`, `"drop"`, `{ retry: true }` after it ingested them again under the same IDs, or `{ replace: { [oldId]: newId } }`. A retry or a replace plans the question again once; an ID still missing then throws `DocumentsNotFoundError`. What it throws fails the question. |
677
+
678
+ A document deleted while a question runs is not an error of the question: the tool tells the model
679
+ it is no longer available, and the question gets a `document_gone` notice.
680
+
681
+ ## Your users' words: `errorInfoOf`
682
+
683
+ New in 0.9.0. `errorInfoOf(error)` tells what any error of the library means, in one record: a
684
+ `category`, a `code`, the HTTP `status` to answer with, whether it is `retryable` and after how
685
+ long (`retryAfterMs`), and an English `message` that is safe to show. It never throws, and it reads
686
+ the errors of another copy of the package too. Every row is in
687
+ [the reference](../reference/errors-and-retries.md#errorinfooferror).
688
+
689
+ | `category` | What failed | `code` |
690
+ |---|---|---|
691
+ | `"ingest"` | A file the library refused (`IngestError`). | Its `IngestErrorCode`: `"too_large"`, `"no_text"`, `"busy"`… |
692
+ | `"store"` | The store, just now (`DocumentStoreError`). Retry. | The system error's code, when there is one. |
693
+ | `"missing"` | Documents that are gone (`DocumentsNotFoundError`), or the chat's folder (`DocumentScopeError` `"scope_missing"`). | `"documents_missing"`, `"scope_missing"`. |
694
+ | `"model"` | A model request (`ModelRequestError`). | Its [kind](#the-kind-of-a-model-error). |
695
+ | `"aborted"` | A signal stopped it: the user left, or a deadline. | `"aborted"`, `"timeout"`. |
696
+ | `"input"` | A mistake in the call: a bug of your server, not of the user. | A scope error's code. |
697
+ | `"unknown"` | Anything else. | A system error's code. |
698
+
699
+ One switch turns them into your users' words. A chatbot for Hebrew speakers:
700
+
701
+ ```ts
702
+ import { errorInfoOf, type ErrorInfo } from "llm-large-files";
703
+
704
+ /** What to answer a Hebrew-speaking user: the status, the words, and when to try again. */
705
+ export function hebrewAnswer(error: unknown): { status: number; message: string; retryAfterMs?: number } {
706
+ const info = errorInfoOf(error);
707
+ return { status: info.status, message: hebrewMessage(info), ...(info.retryAfterMs !== undefined ? { retryAfterMs: info.retryAfterMs } : {}) };
708
+ }
709
+
710
+ function hebrewMessage(info: ErrorInfo): string {
711
+ switch (info.category) {
712
+ case "ingest":
713
+ switch (info.code) {
714
+ case "empty": return "הקובץ ריק.";
715
+ case "too_large": return "הקובץ גדול מדי.";
716
+ case "too_much_text": return "יש בקובץ יותר מדי טקסט.";
717
+ case "too_many_pages": return "יש בקובץ יותר מדי עמודים.";
718
+ case "not_text": return "לא ניתן לקרוא קובץ מסוג זה. צרפו קובץ טקסט, PDF, Word, PowerPoint או Excel.";
719
+ case "compressed": return "הקובץ דחוס. חלצו אותו וצרפו את הקובץ שבתוכו.";
720
+ case "legacy_office": return "זהו קובץ Office ישן או מוגן בסיסמה. שמרו אותו מחדש וצרפו שוב.";
721
+ case "encrypted": return "קובץ ה-PDF מוגן בסיסמה.";
722
+ case "no_text": return "לא נמצא טקסט בקובץ. ייתכן שזהו מסמך סרוק.";
723
+ case "busy": return "השרת עמוס כרגע. נסו שוב בעוד רגע.";
724
+ case "exists": return "הקובץ הזה כבר צורף.";
725
+ default: return "לא ניתן לקרוא את הקובץ.";
726
+ }
727
+ case "store":
728
+ return "לא ניתן לגשת לקבצים כרגע. נסו שוב בעוד רגע.";
729
+ case "missing":
730
+ return info.code === "scope_missing" ? "השיחה הזו כבר לא קיימת." : "אחד הקבצים כבר לא זמין. צרפו אותו שוב.";
731
+ case "model":
732
+ switch (info.code) {
733
+ case "context_overflow": return "השיחה ארוכה מדי. פתחו שיחה חדשה, או שאלו על פחות קבצים.";
734
+ case "rate_limit": return "העוזר עמוס כרגע. נסו שוב בעוד דקה.";
735
+ case "timeout": return "התשובה התעכבה יותר מדי. נסו שוב.";
736
+ case "unreachable":
737
+ case "server": return "לא ניתן לקבל תשובה כרגע. נסו שוב.";
738
+ default: return "העוזר אינו זמין כרגע.";
739
+ }
740
+ case "aborted":
741
+ return info.code === "timeout" ? "השאלה ארכה יותר מדי זמן ונעצרה. נסו שוב." : "השאלה נעצרה.";
742
+ default:
743
+ // "input", "unknown", and categories of a later version.
744
+ return "משהו השתבש. נסו שוב מאוחר יותר.";
745
+ }
746
+ }
747
+ ```
748
+
749
+ A page that renders these messages sets `dir="rtl"` on their element (or `dir="auto"`), so that a
750
+ file name in Latin letters inside a sentence stays in its place.
751
+
752
+ Use it where an error reaches your code: the `catch` of a question, and a route of your own that
753
+ ingests files. It also reads the `error` of a `run.error` or `ingest.error` event, which is plain
754
+ data (`EventError`), so a stream to the browser can carry the same words. It reads such data by its
755
+ `code` (a refused file, a scope), its `name` (a store, documents or a scope) and its `kind` (a
756
+ model). A model's error always has its `kind` there: an error of an adapter of your own that has a
757
+ `status` (0, or 400 to 599) and no `kind` gets the kind its status, message and `code` give, as
758
+ `errorInfoOf` gives it for the error itself (`"rate_limit"` for a 429, `"quota"` for a 429 of code
759
+ `"insufficient_quota"`, `"server"` for a 503, `"auth"` for a 401). A system error's event (a path
760
+ `ingest` could not read: "The file could not be read from storage (ELOOP).") gives its code, as the
761
+ error does. Data with none of them
762
+ is `"unknown"`, with its `status` kept when it is 400 to 599 (a hook of yours that threw a `409`),
763
+ and `retryable` for 429, 502, 503 and 504:
764
+
765
+ ```ts
766
+ import type { ServerResponse } from "node:http";
767
+ import { askStream, errorInfoOf, type AskOptions } from "llm-large-files";
768
+ import { sseMessageOf, writeSseEvents } from "llm-large-files/node";
769
+
770
+ export async function streamInHebrew(res: ServerResponse, options: AskOptions): Promise<void> {
771
+ await writeSseEvents(res, askStream(options), {
772
+ map: (event) => sseMessageOf(event.type === "run.error"
773
+ ? { ...event, error: { ...event.error, message: hebrewMessage(errorInfoOf(event.error)) } }
774
+ : event),
775
+ });
776
+ }
777
+ ```
778
+
779
+ The upload handlers of `llm-large-files/node` answer in English. To answer in Hebrew there, ingest
780
+ in a route of your own and answer with `hebrewAnswer(error)`, or word the `error` of the JSON answer
781
+ and of `ingest.error` in the browser, by its status and `code`. The `ingest.error` of the handlers
782
+ also has the `name` of a store that failed (`"DocumentStoreError"`) and of a scope error
783
+ (`"DocumentScopeError"`, with `code` `"scope_missing"` for a deleted chat), and the `kind` of a
784
+ model's error (a `ModelRequestError` that an ingest or a hook of yours threw). So `errorInfoOf`
785
+ reads it as the handler answered the error, with the status of the JSON answer: a deleted chat is
786
+ `"missing"` and 404, a model that was busy `"model"`, `"rate_limit"` and 429. The event has no
787
+ `retryAfterMs`: the JSON answer sends the wait as `Retry-After`.
651
788
 
652
789
  ## Putting it together: a chat route
653
790
 
@@ -664,6 +801,7 @@ type Failure = { status: number; message: string; retryAfterSeconds?: number };
664
801
 
665
802
  /** What to tell the user about an error of a question, and the HTTP status to answer with. */
666
803
  export function toUserError(error: unknown): Failure {
804
+ // With onMissingDocuments: "drop", a question answers without its missing files instead.
667
805
  if (error instanceof DocumentsNotFoundError) {
668
806
  return { status: 404, message: "A file of this chat is no longer available. Attach it again." };
669
807
  }
@@ -701,7 +701,7 @@ refusing a whole-file read that would pass a ceiling of the question before it s
701
701
 
702
702
  ### The steps
703
703
 
704
- 1. **Plan.** `files.prepare(documentIds, base, { owner, viewPages, wholeDocumentAnalysis, budget })`.
704
+ 1. **Plan.** `files.prepare(documentIds, base, { owner, scope, viewPages, wholeDocumentAnalysis, budget })`.
705
705
  `base` is the size of the rest of the request, `{ tokens, bytes }`: the system prompt and the
706
706
  conversation, with a margin for what frames them (`askWithFiles` adds 2,000 tokens and 8,000
707
707
  bytes). The documents are fitted into what the budget leaves. Pass `wholeDocumentAnalysis: false`
@@ -709,7 +709,9 @@ refusing a whole-file read that would pass a ceiling of the question before it s
709
709
  `analyze_whole_document`, and the cards do not offer a whole-file read. The result is a
710
710
  `PreparedContext`:
711
711
  - `missing`: IDs that were never uploaded, were deleted, have expired, or belong to another
712
- owner. Stop and ask for them again. `askWithFiles` throws `DocumentsNotFoundError` here.
712
+ owner or scope. Stop and ask for them again. `askWithFiles` throws `DocumentsNotFoundError`
713
+ here, unless its `onMissingDocuments` says to answer without them (the plan you got is already
714
+ made without them) or brings them back (plan again).
713
715
  - `blocks`: for each document, its whole text or its card. Put them at the start of the first
714
716
  user turn, in the order of your IDs.
715
717
  - `instruction`: the guide to the tools, for the system prompt. Empty when there is nothing to
@@ -721,7 +723,7 @@ refusing a whole-file read that would pass a ceiling of the question before it s
721
723
  2. **No tools needed?** When `plan.searchable` and `viewable` are both empty, every document is in
722
724
  the prompt: send one request without tools.
723
725
  3. **Tools.** `files.tools(prepared.plan.searchable, options)` gives a `ToolSet`. The options that
724
- matter here: `generate` (a `GenerateText`, which turns on `analyze_whole_document`; without it,
726
+ matter here: `access` (the owner and scope of step 1), `generate` (a `GenerateText`, which turns on `analyze_whole_document`; without it,
725
727
  plan with `wholeDocumentAnalysis: false` in step 1), `viewPages` (pass `prepared.viewable`, and
726
728
  only when your loop sends files to the model), `signal`, `onProgress` (progress of whole-file
727
729
  reads, for every call; per call, see [`ToolCallHooks`](#progress-of-each-call-toolcallhooks)),
@@ -730,12 +732,14 @@ refusing a whole-file read that would pass a ceiling of the question before it s
730
732
  searches belong to it. The full list is in the
731
733
  [library reference](../reference/library.md#tooloptions).
732
734
 
733
- Pass `tools()` only metadata that came back for this user: `prepared.plan.searchable` and
734
- `prepared.viewable` from `prepare(ids, base, { owner })`, or `getMeta(id, { owner })`. The tool
735
- set takes no owner option: the model can reach every document it is given, and each call
736
- compares the owner stored with the document with the `owner` of the metadata it was handed.
737
- Metadata built from IDs the client sent, without the stored owner, reads nothing of a document
738
- that has one: each call answers `doc_… is no longer available on the server. …`.
735
+ Pass `access: { owner, scope }`, new in 0.9.0: each call then asks the store for the document
736
+ with that owner and scope, and checks the ones the store holds against them, whatever the
737
+ metadata handed in says. A document of another owner or scope reads nothing: each call answers
738
+ `doc_… is no longer available on the server. …`. Under `requireOwner` or `requireScope`, `tools()`
739
+ throws without it. Without `access`, as before 0.9.0, each call compares the owner and scope
740
+ stored with the document with those of the metadata it was handed, so pass `tools()` only
741
+ metadata that came back for this user: `prepared.plan.searchable` and `prepared.viewable` from
742
+ `prepare(ids, base, { owner, scope })`, or `getMeta(id, { owner, scope })`.
739
743
  4. **Offer** `tools.declarations` in your provider's form. Gemini takes them as
740
744
  `functionDeclarations` (`toGeminiTools`), the OpenAI-compatible adapter sends each as
741
745
  `{ type: "function", function: declaration }`, and the Claude adapter as
@@ -866,6 +870,8 @@ export async function ask(question: string, documentIds: string[], owner: string
866
870
  const needsTools = prepared.plan.searchable.length > 0 || prepared.viewable.length > 0;
867
871
  const readPart = createGeminiGenerateText({ url: endpoint.url, headers: endpoint.headers });
868
872
  const tools = files.tools(prepared.plan.searchable, {
873
+ // The store's owner of each document is checked against this one on every call.
874
+ access: { owner },
869
875
  // Part reads of analyze_whole_document, counted with the chat's requests.
870
876
  generate: (request) => readPart({ ...request, onUsage: (used) => usage.add(MODEL, used) }),
871
877
  viewPages: prepared.viewable,
@@ -962,6 +968,10 @@ into. Fill it from your own request, as the sample above does:
962
968
  - `maxRequests`: what your ceiling on requests has left, for a whole-file read. It only limits how
963
969
  many parts refused as too large are read again as two halves: a read that needs more parts than
964
970
  this still makes all of them, the merges of their notes and an answer.
971
+ - `maxWaitMs` (new in 0.9.0): the most a look at pages waits for its turn, when that is less than
972
+ the library's `pageLookWaitMs`. `askWithFiles` gives 0 to the looks of a turn after one was told
973
+ the server is busy (`onPagesBusy`, below), so that a wait that ends busy comes once in a turn. Do
974
+ the same in your loop.
965
975
 
966
976
  The defaults, the floors and the errors a call answers with are in the
967
977
  [tools reference](../reference/tools.md#toolcalllimits).
@@ -981,7 +991,14 @@ listeners for one call as the fourth argument of `executeWithFiles`
981
991
  once when it ends. `usage` is what the part reader passed to `onUsage` for that request, so you
982
992
  can show or count the cost of each read.
983
993
 
984
- Only `analyze_whole_document` calls them; the other tools ignore them.
994
+ Only `analyze_whole_document` calls them; the other tools ignore them. Two more, new in 0.9.0,
995
+ are called by any tool:
996
+
997
+ - `onDocumentGone(documentId)`: the document was deleted or expired after you planned the request.
998
+ The call's result tells the model so. Tell the user, or take it off the chat.
999
+ - `onPagesBusy(documentId)`: a look at pages waited longer than `pageLookWaitMs` for its turn
1000
+ (`maxConcurrentPageLooks` of the library) and was not run. The result tells the model the server
1001
+ is busy.
985
1002
 
986
1003
  ```ts
987
1004
  import type { ToolCall, ToolCallHooks, ToolCallLimits, ToolOutput, ToolSet } from "llm-large-files";
@@ -12,7 +12,7 @@ on every server that ingests files:
12
12
 
13
13
  ```bash
14
14
  npm install jszip # DOCX, PPTX and XLSX
15
- npm install unpdf # PDF text (on Node 20 and 22, name a version: see below)
15
+ npm install unpdf # PDF text (on Node 22, name a version: see below)
16
16
  npm install @cantoo/pdf-lib # PDF picture marks, page check, and view_pages
17
17
  ```
18
18
 
@@ -20,12 +20,11 @@ They are optional peer dependencies of the package: `jszip` ^3.10.0, `unpdf` ^1.
20
20
  and `@cantoo/pdf-lib` ^2.11.1.
21
21
 
22
22
  Not every `unpdf` runs on every Node. unpdf 2 asks for Node 24, and on Node 24 and later
23
- `npm install unpdf` installs it. On Node 20 and 22, install a version that runs there:
23
+ `npm install unpdf` installs it. On Node 22, install a version that runs there:
24
24
 
25
25
  | Node | `unpdf` to install | Refused at the first PDF ([What is refused](#what-is-refused)) |
26
26
  |---|---|---|
27
- | 20 | 1.4.0, or 1.6.1 to 1.8.1: `npm install unpdf@1.7.0`. 1.7.0 is the last that does not ask for Node 22. | 1.5.0 to 1.6.0, which would stop the whole process; 1.9 and later, 2.x included, which cannot load pdf.js on Node 20 |
28
- | 22 | 1.4.0, or 1.6.1 or a later 1.x: `npm install unpdf@1` | 1.5.0 to 1.6.0 |
27
+ | 22 | 1.4.0, or 1.6.1 or a later 1.x: `npm install unpdf@1` | 1.5.0 to 1.6.0, which would stop the whole process |
29
28
  | 24 and later | Any version from 1.4.0, 2.x included: `npm install unpdf` | None |
30
29
 
31
30
  The 12 test PDFs of the package give the same text, pages, picture marks and page cuts with every
@@ -257,11 +256,19 @@ all, and an XLSX was refused as a ZIP archive.
257
256
 
258
257
  `files.ingest` throws an [`IngestError`](../reference/library.md#ingesterror) whose message is
259
258
  meant for the user, with a `code` for your application. `createDocumentHandlers` answers it with
260
- HTTP 422 and that message, except a file over `maxUploadBytes`, which the upload route refuses
261
- before reading it all: HTTP 413, `The file is larger than the 100 MB upload limit.`
262
- ([node reference](../reference/node.md)). For a damaged file the message is the reader's own, from
263
- pdf.js or jszip, and not written for a user, with the code `"unreadable"`: an application that
264
- wants friendlier wording maps the codes itself.
259
+ HTTP 422 and that message, with two exceptions:
260
+
261
+ - A file over `maxUploadBytes`, which the upload route refuses before reading it all: HTTP 413,
262
+ `The file is larger than the 100 MB upload limit.` ([node reference](../reference/node.md)).
263
+ - A file of code `"unreadable"`: a damaged file, whose message is the reader's own (from pdf.js or
264
+ jszip, and not written for a user), a DOCX or XLSX without its main part, and an error of an
265
+ extractor of your own that the library does not know. Since 0.9.0 the upload route,
266
+ `uploadAnswerOf` and `errorInfoOf` answer it in fixed words: `This file could not be read. It may
267
+ be damaged, or not of the type its name says.` The message below stays on the error, for your
268
+ log.
269
+
270
+ An application that wants other wording maps the codes itself
271
+ ([`errorInfoOf`](./errors-and-reliability.md#your-users-words-errorinfoof)).
265
272
 
266
273
  | What | Message |
267
274
  |---|---|
@@ -293,16 +300,14 @@ wants friendlier wording maps the codes itself.
293
300
  | A file that takes longer than `ingestTimeoutMs` to read (2 minutes by default) | `report.pdf took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.` |
294
301
  | A PDF without text on any page | See [Scanned PDFs](#scanned-pdfs). |
295
302
  | A PDF that needs a password to open | `This PDF is protected by a password, so it cannot be read. Open it, print it to a new PDF without the password, and attach that.` Until 0.8.0, `No password given`, the message of pdf.js. |
296
- | A damaged PDF | The message of pdf.js, such as `Invalid PDF structure.` |
297
- | A damaged DOCX, PPTX or XLSX, or one that is not a ZIP | The message of jszip, such as `Can't find end of central directory : is this a zip file ? …` |
298
- | A DOCX without `word/document.xml` | `This DOCX does not contain word/document.xml.` |
303
+ | A damaged PDF | The message of pdf.js, such as `Invalid PDF structure.` Code `"unreadable"`: the upload route answers in fixed words (above). |
304
+ | A damaged DOCX, PPTX or XLSX, or one that is not a ZIP | The message of jszip, such as `Can't find end of central directory : is this a zip file ? …` Code `"unreadable"`: the upload route answers in fixed words. |
305
+ | A DOCX without `word/document.xml` | `This DOCX does not contain word/document.xml.` Code `"unreadable"`: the upload route answers in fixed words. |
299
306
  | A PPTX without slides | `This PPTX does not contain any slides.` |
300
- | An XLSX without `xl/workbook.xml`, or without sheets | `This XLSX does not contain xl/workbook.xml.`, `This XLSX does not contain any sheets with cells.` |
307
+ | An XLSX without `xl/workbook.xml`, or without sheets | `This XLSX does not contain xl/workbook.xml.` (code `"unreadable"`: the upload route answers in fixed words), `This XLSX does not contain any sheets with cells.` |
301
308
  | A DOCX, PPTX or XLSX without `jszip` installed | `Reading DOCX, PPTX and XLSX files needs the optional dependency "jszip".` |
302
309
  | A PDF without `unpdf` installed | `Reading PDF files needs the optional dependency "unpdf".` |
303
310
  | A PDF, with `unpdf` 1.5.0 to 1.6.0 on Node 22 or 23, which would stop the whole process at the first PDF (0.5.0 did stop) | `The unpdf installed would stop the whole server at the first PDF file on Node 22, so PDF files are not read. Install unpdf 1.6.1 or later, or run Node 24 or later.` |
304
- | The same on Node 20 | `The unpdf installed would stop the whole server at the first PDF file on Node 20, so PDF files are not read. Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 24 or later.` |
305
- | A PDF, with `unpdf` 1.9 or later (2.x included) on Node 20, which cannot load pdf.js there | `The unpdf installed cannot read PDF files on Node 20 (Serverless PDF.js bundle could not be resolved: ReferenceError: Iterator is not defined). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.` The part in parentheses is unpdf's own message: with unpdf 2 it is `PDF.js could not be resolved: ReferenceError: Iterator is not defined`. |
306
311
 
307
312
  A missing dependency, or an `unpdf` that does not run on your Node, is your server's fault, but it
308
313
  reaches the user as a 422, a file that cannot be read. Install the dependencies wherever the upload
@@ -422,8 +427,9 @@ the rebuilt rows 110 ([measurements](../measurements.md)).
422
427
  What it handles: empty cells, tables inside one column of a two-column page, right-to-left tables
423
428
  (the first column is the rightmost), tables printed sideways, rotated pages, footnote marks,
424
429
  headings that span columns, and cells whose text wraps onto several lines when the rows are visibly
425
- spaced apart. Text that is not a table (paragraphs, lists, columns of prose, justified text) is left
426
- as pdf.js gives it.
430
+ spaced apart. A cell that mixes the two directions (a Latin name in a Hebrew table, a Hebrew phrase
431
+ in an English one) keeps each run of words in its reading order. Text that is not a table
432
+ (paragraphs, lists, columns of prose, justified text) is left as pdf.js gives it.
427
433
 
428
434
  It is cautious: where the evidence for a table is weak, the text stays as it was. So:
429
435
 
@@ -467,8 +473,9 @@ close that gap:
467
473
 
468
474
  1. **A line in the text that says where the pictures are.** It needs `@cantoo/pdf-lib`.
469
475
  2. **A tool, `view_pages`, that hands the model the real pages** as a small PDF, when it asks. It
470
- needs `@cantoo/pdf-lib` and the uploaded file itself, which the store keeps when you list
471
- `"pdf"` in `keepOriginals`.
476
+ needs `@cantoo/pdf-lib` and the uploaded file itself, which is kept when you list `"pdf"` in
477
+ `keepOriginals`: by the store, or, since 0.9.0, where your application keeps it
478
+ ([below](#view_pages-from-your-own-uploads)).
472
479
 
473
480
  ```ts
474
481
  import { createLargeFiles, FileDocumentStore } from "llm-large-files";
@@ -491,6 +498,7 @@ The options of this page, and where each is explained:
491
498
  | Option | Default | What it does |
492
499
  |---|---|---|
493
500
  | `keepOriginals` (`createLargeFiles`) | `[]`: no file kept | List `"pdf"` to keep the uploaded file, which `view_pages` and scanned PDFs need ([above](#pictures-in-pdfs)). |
501
+ | `originals` (`createLargeFiles`) | none | Reads the uploads your application keeps, so the store keeps no copy ([`view_pages` from your own uploads](#view_pages-from-your-own-uploads)). New in 0.9.0. |
494
502
  | `scannedPdfPages` (`createLargeFiles`) | 30 | The most pages a PDF without text may have to be accepted, when PDFs are kept. 0 refuses every one ([Scanned PDFs](#scanned-pdfs)). |
495
503
  | `maxPdfPages`, `maxTextBytes`, `ingestTimeoutMs` (`createLargeFiles`) | 5,000 pages; 100 MB, or `maxUploadBytes` when that is larger; 120,000 ms | The most pages, text and time one file may take at ingest ([What is refused](#what-is-refused)). |
496
504
  | `tables`, `pictures` (`createPdfExtractor`) | `true` | Rebuild tables; write the line that marks a page with a picture ([PDF tables](#pdf-tables), [The line that marks a page](#the-line-that-marks-a-page)). |
@@ -659,6 +667,81 @@ block:
659
667
  A look runs on the server that answers the question, not where the file was ingested
660
668
  ([Deployment](./deployment.md#pages-of-pdfs)).
661
669
 
670
+ **Looks take their turns** (new in 0.9.0). Looks share the thread of your server, so more of them
671
+ at once do not finish sooner: six at once each took about four times as long, and held 352 MB more
672
+ than one. So one look runs at a time in a library, over all its questions, and the others wait in
673
+ order, before their PDF is loaded:
674
+
675
+ | Option (`createLargeFiles`) | Default | What it does |
676
+ |---|---|---|
677
+ | `maxConcurrentPageLooks` | 1 | How many looks run at once. `Infinity` for no limit, as before 0.9.0. |
678
+ | `pageLookWaitMs` | 30,000 | How long a look waits for its turn. Past it, it is not run. |
679
+
680
+ A look that waited too long tells the model "report.pdf: The pages cannot be looked at right now;
681
+ the server is busy. Answer from the text, or look again later.", and the question gets a
682
+ `page_looks_busy` notice ([events](../reference/events.md#noticecode-and-noticedisplay)). A
683
+ question that is stopped stops waiting at once, and loads nothing. A question stopped while its
684
+ PDF is read gives the turn back at once, and no pages are cut for it.
685
+
686
+ A look holds its turn while it reads the PDF from the store, for at most `ingestTimeoutMs` (2
687
+ minutes by default). Past it, the turn goes back, the next look runs, and the model reads "The
688
+ original file of report.pdf could not be read in time, so its pages cannot be shown. Answer from
689
+ the text." Give your store's `getOriginal` a time limit of its own: the read goes on.
690
+
691
+ How long a question can wait for turns:
692
+
693
+ - A look waits at most `pageLookWaitMs` (30 s) for its turn. A wait that ends with "busy" happens
694
+ at most once in a tool turn: after a look of the turn was told the server is busy, the other
695
+ looks of that turn do not wait. Each runs if a turn is free at that moment, and is told the
696
+ server is busy if not.
697
+ - A look that gets its turn may still have waited for it up to `pageLookWaitMs`. So when other
698
+ questions hold the turn all that time, a tool turn can wait up to `pageLookWaitMs` for each of its
699
+ looks: 8 looks of 30 s, 4 minutes, with the defaults (`callsPerTurn` 8), and a question waits that
700
+ in each tool turn that looks at pages.
701
+ - Lower `pageLookWaitMs`, or raise `maxConcurrentPageLooks`, for a chat that must answer sooner.
702
+
703
+ ### `view_pages` from your own uploads
704
+
705
+ New in 0.9.0. When your application keeps each upload anyway, the store need not keep a second
706
+ copy of the PDF. Give the ingest where the file is (`original: { ref }`), and the library a reader
707
+ of your uploads (`originals`): `fileOriginals(root)` of `llm-large-files/node` reads them from a
708
+ folder.
709
+
710
+ ```ts
711
+ import path from "node:path";
712
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
713
+ import { fileOriginals } from "llm-large-files/node";
714
+
715
+ const VOLUME = process.env.DOCUMENTS_DIR!;
716
+
717
+ export const files = createLargeFiles({
718
+ store: new FileDocumentStore(VOLUME, { scopes: { depth: 2 } }),
719
+ keepOriginals: ["pdf"],
720
+ originals: fileOriginals(VOLUME),
721
+ });
722
+
723
+ /** Ingests a PDF your upload route saved under <VOLUME>/<user>/<chat>/uploads/. */
724
+ export function ingestSaved(userId: string, chatId: string, uploadId: string, name: string) {
725
+ const ref = `${userId}/${chatId}/uploads/${uploadId}`;
726
+ return files.ingest({ name, source: { path: path.join(VOLUME, ref) }, original: { ref }, owner: userId, scope: [userId, chatId], id: uploadId });
727
+ }
728
+ ```
729
+
730
+ - The model sees nothing of this: the ref is never in the prompt, the cards or the results.
731
+ - A look reads the file through the reader, within its turn and its time, as it reads a copy from
732
+ the store. The metadata records the size and SHA-256 the file had at ingest, and the look
733
+ compares them. A file that has changed since (saved again under the same name, cut short, edited)
734
+ is not cut, and the model reads "report.pdf changed on the server since it was read. Attach it
735
+ again to look at its pages.": its pages would not match the text the model has. A file that is
736
+ gone reads as "The original file of report.pdf is no longer on the server, so its pages cannot
737
+ be shown. Answer from the text."
738
+ - `files.delete` and the sweep never touch your upload. Remove it with its chat.
739
+ - A scanned PDF is accepted with a ref as with a copy in the store ([Scanned PDFs](#scanned-pdfs)),
740
+ even over a store without `putOriginal`.
741
+ - [Storage](./storage.md#keeping-the-uploaded-files) has the rules for the ref and a reader of your
742
+ own, and [Security](../security.md#originals-your-application-keeps) what `fileOriginals`
743
+ refuses.
744
+
662
745
  ### Limits and cost
663
746
 
664
747
  | Limit | Value | When it is reached |
@@ -785,7 +868,8 @@ refuses text before a tool result.
785
868
 
786
869
  The model gets `view_pages` for a PDF only when all of these hold:
787
870
 
788
- - `keepOriginals` lists `"pdf"`, and the store has `putOriginal` and `getOriginal`.
871
+ - `keepOriginals` lists `"pdf"`, and the store has `putOriginal` and `getOriginal`, or (0.9.0)
872
+ the document was ingested with `original` and the library has `originals`.
789
873
  `FileDocumentStore` and `MemoryDocumentStore` have both. Documents ingested before you turned it
790
874
  on have no file kept: upload them again. `meta.originalKept` says whether a document has one.
791
875
  - Every model of the question can be sent a file: not `openAiCompatible()` without `pdfInput`, not
@@ -827,7 +911,8 @@ export const files = createLargeFiles({
827
911
  });
828
912
  ```
829
913
 
830
- `scannedPdfPages` has an effect only when PDFs are kept, by a store that can keep them. A PDF with
914
+ `scannedPdfPages` has an effect only when PDFs are kept: by a store that can keep them, or (0.9.0)
915
+ by their ref, for an ingest with `original` in a library with `originals`. A PDF with
831
916
  text on any page is always accepted, however many of its pages are scans: those pages say that they
832
917
  have no text, and with the file kept the model can look at them.
833
918
 
@@ -879,13 +964,21 @@ What the library does with what you return:
879
964
  - A `text` file whose lines look like a log becomes `log`.
880
965
 
881
966
  An error you throw is the answer to the upload. `ingest` throws it as an `IngestError` with the
882
- same message (and your error as `cause`), and `createDocumentHandlers` answers 422 with its
883
- message, unless the error has a `status` (or `statusCode`) from 400 to 599: then it answers that
884
- status, with your message. A status of 413 is answered with the upload-limit message instead of
885
- yours. An error with a Node system `code` and `syscall` (from `fs` or a socket) is answered 500,
886
- `Upload failed (ENOENT).`, without its message. A value that is not an `Error`, such as a thrown
887
- string, is answered 500 too: `Upload failed.` Write messages a user can read, and give a status
888
- when the fault is on your side, such as an OCR service that is down.
967
+ same message (and your error as `cause`), with the code its message gives
968
+ ([`ingestErrorCodeOf`](../reference/library.md#ingesterrorcodeofmessage)). `createDocumentHandlers`
969
+ answers 422 with your message only when the message gives a code the library knows ("is protected
970
+ by a password", say). Any other message gives code `"unreadable"`, and since 0.9.0 the answer is
971
+ then 422 in fixed words: `This file could not be read. It may be damaged, or not of the type its
972
+ name says.` Your message stays on the error, for your log ([what is refused](#what-is-refused)). To
973
+ have your own words shown, throw `new IngestError(code, message)` with the code that fits
974
+ ([`Extractor`](../reference/library.md#extractor)).
975
+
976
+ An error with a `status` (or `statusCode`) from 400 to 599 is answered with that status and your
977
+ message. A status of 413 is answered with the upload-limit message instead of yours. An error with
978
+ a Node system `code` and `syscall` (from `fs` or a socket) is answered 500, `Upload failed
979
+ (ENOENT).`, without its message. A value that is not an `Error`, such as a thrown string, is
980
+ answered 500 too: `Upload failed.` Write messages a user can read, and give a status when the fault
981
+ is on your side, such as an OCR service that is down.
889
982
 
890
983
  ### Rules for a PDF extractor
891
984
 
@@ -900,7 +993,8 @@ built-in one does:
900
993
  `@cantoo/pdf-lib` counts another number, since a page number could then point at the wrong page.
901
994
  Without `pages`, that check is not made, and the card and the instruction give no page count.
902
995
  3. **Honour `input.scannedPages`.** The library sets it on every PDF it ingests when PDFs are kept
903
- (`keepOriginals` lists `"pdf"` and the store has `putOriginal`) and `scannedPdfPages` is above 0.
996
+ (`keepOriginals` lists `"pdf"`, and the store has `putOriginal` or the ingest gives `original`
997
+ to a library with `originals`) and `scannedPdfPages` is above 0.
904
998
  It does not say that the file has no text: its value is `scannedPdfPages`, the most pages a PDF
905
999
  without any text may have. Unset, refuse a PDF in which you found no text. The library does not check
906
1000
  this for you: page lines alone are text, so a scan your extractor lets through is stored even