llm-large-files 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +1402 -467
  2. package/README.md +188 -60
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +190 -39
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +60 -4
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1068 -206
  14. package/dist/ask.js.map +1 -1
  15. package/dist/encoding.d.ts +17 -0
  16. package/dist/encoding.d.ts.map +1 -0
  17. package/dist/encoding.js +852 -0
  18. package/dist/encoding.js.map +1 -0
  19. package/dist/errors.d.ts +4 -0
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +15 -0
  22. package/dist/errors.js.map +1 -1
  23. package/dist/events.d.ts +333 -0
  24. package/dist/events.d.ts.map +1 -0
  25. package/dist/events.js +159 -0
  26. package/dist/events.js.map +1 -0
  27. package/dist/evidence.d.ts +2 -0
  28. package/dist/evidence.d.ts.map +1 -1
  29. package/dist/evidence.js +3 -2
  30. package/dist/evidence.js.map +1 -1
  31. package/dist/extract.d.ts +35 -3
  32. package/dist/extract.d.ts.map +1 -1
  33. package/dist/extract.js +626 -58
  34. package/dist/extract.js.map +1 -1
  35. package/dist/gemini/adapter.d.ts +17 -8
  36. package/dist/gemini/adapter.d.ts.map +1 -1
  37. package/dist/gemini/adapter.js +108 -61
  38. package/dist/gemini/adapter.js.map +1 -1
  39. package/dist/gemini/chat.d.ts +23 -3
  40. package/dist/gemini/chat.d.ts.map +1 -1
  41. package/dist/gemini/chat.js +6 -2
  42. package/dist/gemini/chat.js.map +1 -1
  43. package/dist/gemini/errors.d.ts +9 -4
  44. package/dist/gemini/errors.d.ts.map +1 -1
  45. package/dist/gemini/errors.js +32 -0
  46. package/dist/gemini/errors.js.map +1 -1
  47. package/dist/gemini/generate.d.ts +10 -2
  48. package/dist/gemini/generate.d.ts.map +1 -1
  49. package/dist/gemini/generate.js +13 -7
  50. package/dist/gemini/generate.js.map +1 -1
  51. package/dist/gemini/index.d.ts +3 -3
  52. package/dist/gemini/index.d.ts.map +1 -1
  53. package/dist/gemini/index.js +2 -2
  54. package/dist/gemini/index.js.map +1 -1
  55. package/dist/gemini/sse.d.ts +1 -1
  56. package/dist/gemini/sse.d.ts.map +1 -1
  57. package/dist/gemini/sse.js +1 -1
  58. package/dist/gemini/sse.js.map +1 -1
  59. package/dist/http.d.ts +116 -0
  60. package/dist/http.d.ts.map +1 -1
  61. package/dist/http.js +347 -1
  62. package/dist/http.js.map +1 -1
  63. package/dist/index.d.ts +11 -6
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +6 -4
  66. package/dist/index.js.map +1 -1
  67. package/dist/library.d.ts +67 -5
  68. package/dist/library.d.ts.map +1 -1
  69. package/dist/library.js +405 -85
  70. package/dist/library.js.map +1 -1
  71. package/dist/map-reduce.d.ts +28 -1
  72. package/dist/map-reduce.d.ts.map +1 -1
  73. package/dist/map-reduce.js +240 -52
  74. package/dist/map-reduce.js.map +1 -1
  75. package/dist/model.d.ts +84 -2
  76. package/dist/model.d.ts.map +1 -1
  77. package/dist/model.js +182 -1
  78. package/dist/model.js.map +1 -1
  79. package/dist/node/handlers.d.ts +20 -4
  80. package/dist/node/handlers.d.ts.map +1 -1
  81. package/dist/node/handlers.js +122 -20
  82. package/dist/node/handlers.js.map +1 -1
  83. package/dist/node/index.d.ts +2 -0
  84. package/dist/node/index.d.ts.map +1 -1
  85. package/dist/node/index.js +1 -0
  86. package/dist/node/index.js.map +1 -1
  87. package/dist/node/sse.d.ts +59 -0
  88. package/dist/node/sse.d.ts.map +1 -0
  89. package/dist/node/sse.js +174 -0
  90. package/dist/node/sse.js.map +1 -0
  91. package/dist/openai/adapter.d.ts +29 -5
  92. package/dist/openai/adapter.d.ts.map +1 -1
  93. package/dist/openai/adapter.js +311 -37
  94. package/dist/openai/adapter.js.map +1 -1
  95. package/dist/output-limit.d.ts +14 -2
  96. package/dist/output-limit.d.ts.map +1 -1
  97. package/dist/output-limit.js +39 -10
  98. package/dist/output-limit.js.map +1 -1
  99. package/dist/pause.d.ts +24 -0
  100. package/dist/pause.d.ts.map +1 -0
  101. package/dist/pause.js +38 -0
  102. package/dist/pause.js.map +1 -0
  103. package/dist/pdf-pages.d.ts +32 -2
  104. package/dist/pdf-pages.d.ts.map +1 -1
  105. package/dist/pdf-pages.js +275 -14
  106. package/dist/pdf-pages.js.map +1 -1
  107. package/dist/pdf-pictures.d.ts +30 -3
  108. package/dist/pdf-pictures.d.ts.map +1 -1
  109. package/dist/pdf-pictures.js +50 -8
  110. package/dist/pdf-pictures.js.map +1 -1
  111. package/dist/pdf-work.d.ts +40 -0
  112. package/dist/pdf-work.d.ts.map +1 -0
  113. package/dist/pdf-work.js +734 -0
  114. package/dist/pdf-work.js.map +1 -0
  115. package/dist/plan.d.ts +22 -4
  116. package/dist/plan.d.ts.map +1 -1
  117. package/dist/plan.js +61 -12
  118. package/dist/plan.js.map +1 -1
  119. package/dist/retry.d.ts +23 -1
  120. package/dist/retry.d.ts.map +1 -1
  121. package/dist/retry.js +33 -3
  122. package/dist/retry.js.map +1 -1
  123. package/dist/search.d.ts +8 -2
  124. package/dist/search.d.ts.map +1 -1
  125. package/dist/search.js +60 -10
  126. package/dist/search.js.map +1 -1
  127. package/dist/sse.d.ts +35 -2
  128. package/dist/sse.d.ts.map +1 -1
  129. package/dist/sse.js +145 -31
  130. package/dist/sse.js.map +1 -1
  131. package/dist/stores.d.ts.map +1 -1
  132. package/dist/stores.js +5 -2
  133. package/dist/stores.js.map +1 -1
  134. package/dist/text-index.d.ts +6 -0
  135. package/dist/text-index.d.ts.map +1 -1
  136. package/dist/text-index.js +25 -8
  137. package/dist/text-index.js.map +1 -1
  138. package/dist/text.d.ts +62 -2
  139. package/dist/text.d.ts.map +1 -1
  140. package/dist/text.js +314 -14
  141. package/dist/text.js.map +1 -1
  142. package/dist/tools.d.ts +61 -1
  143. package/dist/tools.d.ts.map +1 -1
  144. package/dist/tools.js +269 -42
  145. package/dist/tools.js.map +1 -1
  146. package/dist/types.d.ts +102 -3
  147. package/dist/types.d.ts.map +1 -1
  148. package/dist/zip-directory.d.ts +43 -0
  149. package/dist/zip-directory.d.ts.map +1 -0
  150. package/dist/zip-directory.js +130 -0
  151. package/dist/zip-directory.js.map +1 -0
  152. package/docs/README.md +288 -0
  153. package/docs/api.md +37 -381
  154. package/docs/configuration.md +28 -558
  155. package/docs/getting-started.md +407 -223
  156. package/docs/guides/anthropic.md +590 -0
  157. package/docs/guides/conversations.md +629 -0
  158. package/docs/guides/costs-and-limits.md +726 -0
  159. package/docs/guides/deployment.md +654 -0
  160. package/docs/guides/errors-and-reliability.md +735 -0
  161. package/docs/guides/explorer-model.md +399 -0
  162. package/docs/guides/openai-compatible.md +602 -0
  163. package/docs/guides/own-adapter-and-loop.md +1169 -0
  164. package/docs/guides/pdfs.md +971 -0
  165. package/docs/guides/storage.md +731 -0
  166. package/docs/guides/testing.md +1199 -0
  167. package/docs/guides/vertex-and-gemini.md +717 -0
  168. package/docs/guides/web-app.md +1589 -0
  169. package/docs/how-it-works.md +1012 -164
  170. package/docs/measurements.md +881 -0
  171. package/docs/publishing.md +274 -46
  172. package/docs/reference/anthropic.md +427 -0
  173. package/docs/reference/ask.md +892 -0
  174. package/docs/reference/errors-and-retries.md +758 -0
  175. package/docs/reference/events.md +993 -0
  176. package/docs/reference/gemini.md +823 -0
  177. package/docs/reference/library.md +1467 -0
  178. package/docs/reference/node.md +528 -0
  179. package/docs/reference/openai.md +385 -0
  180. package/docs/reference/tools.md +883 -0
  181. package/docs/security.md +897 -103
  182. package/docs/troubleshooting.md +1390 -0
  183. package/package.json +2 -2
  184. package/src/analyze.ts +93 -42
  185. package/src/anthropic/adapter.ts +196 -39
  186. package/src/ask.ts +1087 -202
  187. package/src/encoding.ts +850 -0
  188. package/src/errors.ts +17 -0
  189. package/src/events.ts +442 -0
  190. package/src/evidence.ts +5 -2
  191. package/src/extract.ts +602 -62
  192. package/src/gemini/adapter.ts +118 -65
  193. package/src/gemini/chat.ts +28 -4
  194. package/src/gemini/errors.ts +34 -1
  195. package/src/gemini/generate.ts +23 -10
  196. package/src/gemini/index.ts +3 -3
  197. package/src/gemini/sse.ts +1 -1
  198. package/src/http.ts +376 -1
  199. package/src/index.ts +27 -5
  200. package/src/library.ts +459 -85
  201. package/src/map-reduce.ts +252 -51
  202. package/src/model.ts +236 -3
  203. package/src/node/handlers.ts +137 -22
  204. package/src/node/index.ts +2 -0
  205. package/src/node/sse.ts +198 -0
  206. package/src/openai/adapter.ts +306 -38
  207. package/src/output-limit.ts +44 -8
  208. package/src/pause.ts +41 -0
  209. package/src/pdf-pages.ts +268 -15
  210. package/src/pdf-pictures.ts +56 -9
  211. package/src/pdf-work.ts +722 -0
  212. package/src/plan.ts +68 -12
  213. package/src/retry.ts +49 -5
  214. package/src/search.ts +63 -10
  215. package/src/sse.ts +153 -28
  216. package/src/stores.ts +5 -2
  217. package/src/text-index.ts +26 -7
  218. package/src/text.ts +323 -13
  219. package/src/tools.ts +261 -42
  220. package/src/types.ts +107 -4
  221. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,971 @@
1
+ # PDFs and other formats
2
+
3
+ This guide covers the files the library reads: the formats, what each needs installed, and what the
4
+ model gets from them. Most of it is about PDFs: rebuilt tables, the line that marks a page with a
5
+ picture, `view_pages`, which shows the model the real pages, scanned PDFs, and extractors of your
6
+ own, OCR among them. Exact signatures are in the [library reference](../reference/library.md).
7
+
8
+ ## Formats
9
+
10
+ The readers of DOCX, PPTX and PDF files are optional dependencies. Install the ones you need on
11
+ every server that ingests files:
12
+
13
+ ```bash
14
+ npm install jszip # DOCX and PPTX
15
+ npm install unpdf # PDF text (on Node 20 and 22, name a version: see below)
16
+ npm install @cantoo/pdf-lib # PDF picture marks, page check, and view_pages
17
+ ```
18
+
19
+ They are optional peer dependencies of the package: `jszip` ^3.10.0, `unpdf` ^1.4.0 || ^2.0.0
20
+ and `@cantoo/pdf-lib` ^2.11.1.
21
+
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:
24
+
25
+ | Node | `unpdf` to install | Refused at the first PDF ([What is refused](#what-is-refused)) |
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 |
29
+ | 24 and later | Any version from 1.4.0, 2.x included: `npm install unpdf` | None |
30
+
31
+ The 12 test PDFs of the package give the same text, pages, picture marks and page cuts with every
32
+ `unpdf` from 1.4.0 to 2.2.1, each on a Node it runs on. An app that installs unpdf 2 and goes
33
+ back to llm-large-files 0.5.0 must go back to unpdf 1 in the same command
34
+ (`npm install llm-large-files@0.5.0 unpdf@^1`): 0.5.0 does not accept unpdf 2, and npm stops with
35
+ `ERESOLVE`.
36
+
37
+ | Format | Detected by | Needs | What the text holds |
38
+ |---|---|---|---|
39
+ | `text` | Anything not below | | The file decoded as UTF-8, or as UTF-16 with a byte-order mark. Without the mark, only little-endian UTF-16 of mostly ASCII text is recognised. A file that is not UTF-8 is read in windows-1255, windows-1256, windows-1251, Shift_JIS or windows-1252 when its letters show which one (`meta.encoding`), and as UTF-8 otherwise ([Text encodings](#text-encodings)). Characters that are not valid are stored as U+FFFD (�) and counted (`meta.replacedCharacters`). |
40
+ | `log` | `.log`, `.out`, `.err`; or a `text` file in which at least 40% of the first 200 non-empty lines (5 at least) start with a timestamp or a level | | As `text`, plus a log profile: levels, time range, most frequent errors. |
41
+ | `markdown` | `.md`, `.markdown`, `text/markdown` | | As `text`. Its `#` headings form the outline. |
42
+ | `json` | `.json`, `.jsonl`, `.ndjson`, `application/json` | | As `text`. Minified JSON becomes lines of at most 2,000 characters. |
43
+ | `csv` | `.csv`, `.tsv`, `text/csv` | | As `text`. |
44
+ | `pdf` | `.pdf`, `application/pdf` | `unpdf`; `@cantoo/pdf-lib` for picture marks, the page check and `view_pages` | A `--- Page N ---` line before each page, tables rebuilt as rows of cells, a line for a page without text and for a page with a picture ([PDF text](#pdf-text)). |
45
+ | `docx` | `.docx`, or the Word MIME type | `jszip` | The body, then the endnotes, footers, footnotes and headers, in that order. Text that Word hides comes after the text of its paragraph that shows, each of its lines starting `[Hidden text, not shown in the document]` ([DOCX and PPTX](#docx-and-pptx)). |
46
+ | `pptx` | `.pptx`, or the PowerPoint MIME type | `jszip` | `## Slide N` before each slide, `## Slide N (hidden, not shown in the slide show)` for a slide that the slide show skips, `[No text on this slide]` for a slide without text. |
47
+
48
+ `detectFormat(name, mimeType)` picks the format: a known extension first, then the MIME type, then
49
+ `text`. So `report` with no extension, sent as `application/pdf`, is a PDF, and `data.txt` sent as
50
+ `application/json` is JSON, since `.txt` is not one of the known extensions. HTML, XML, YAML and
51
+ source code are `text`. The MIME type is compared whole: `application/json; charset=utf-8` is not
52
+ JSON. Send the bare type (or `X-File-Type: application/json` to the upload route of
53
+ `createDocumentHandlers`, which takes it before `Content-Type`).
54
+
55
+ Whatever the format, the text is then made uniform: line breaks become `\n`, colour codes and other
56
+ control characters are removed, and lines longer than 2,000 characters are split, so every line can
57
+ be read by its number. Most characters that show nothing are removed too: tag characters,
58
+ zero-width spaces, word joiners, a soft hyphen inside a line, and the text-direction controls that
59
+ reorder what a person sees. Those that scripts and emoji need are kept: the marks of right-to-left
60
+ text (U+200E, U+200F, U+061C), the joiners of emoji and Persian, variation selectors, Hangul
61
+ fillers, and the line and paragraph separators (U+2028, U+2029). A crafted file can still carry
62
+ text that a person does not see in them ([Security](../security.md#characters-that-show-nothing)
63
+ lists them all). In a text with no other line break, such as a mainframe file converted to UTF-8,
64
+ U+0085 (next line) ends a line, except right after a character from U+0080 to U+00FF, where it is
65
+ taken for half of a UTF-8 letter and removed; anywhere else it is removed with the other control
66
+ characters. That is text in UTF-8: the same export converted to ISO-8859-1 is read as
67
+ windows-1252, where its byte 0x85 is "…", and stays one long line, so convert it to UTF-8
68
+ instead. No other line break is added or removed, but a line of more than 2,000 characters
69
+ that lost some of these characters can be split into fewer pieces than 0.5.0 split it, which
70
+ moves the lines after it. Every format but log, JSON and CSV gets an outline from its
71
+ headings: Markdown `#` lines (`## Slide N` among them), chapter and numbered section lines, and
72
+ short lines in capitals. `meta.pages` is the number of pages of a PDF and of slides of a PPTX.
73
+ [How it works](../how-it-works.md) follows ingest from there.
74
+
75
+ ### Text encodings
76
+
77
+ A text, log, CSV, JSON or Markdown file that is not valid UTF-8 is read in the older encoding it
78
+ was saved in, when its letters show which one: Excel saves a Hebrew CSV in windows-1255, and an old
79
+ program writes in the code page of Windows. No text file is refused for its encoding. When no
80
+ encoding fits, the file is read as UTF-8, as 0.5.0 read every file that was not UTF-16, and each
81
+ character that is not valid is stored as U+FFFD (�).
82
+
83
+ | `meta.encoding` | Letters | Also read this way |
84
+ |---|---|---|
85
+ | `windows-1255` | Hebrew | ISO-8859-8 |
86
+ | `windows-1256` | Arabic | |
87
+ | `windows-1251` | Cyrillic | |
88
+ | `shift_jis` | Japanese, half-width katakana too (as in Japanese bank files) | |
89
+ | `windows-1252` | Western European | ISO-8859-1, as browsers read it |
90
+
91
+ How the encoding is chosen:
92
+
93
+ 1. Each line is read as UTF-8. It counts as UTF-8 when it holds at least as many characters of
94
+ more than one byte as characters that are not valid, as not UTF-8 when it holds more that are
95
+ not valid, and as ASCII when it holds neither. A character cut in two by the start or the end
96
+ of the file counts as UTF-8.
97
+ 2. The file is UTF-8 when at least as many lines count as UTF-8 as count as not (ASCII lines count
98
+ for neither), or when at most one line in 200 is not UTF-8 (ASCII lines counted): a log cut at a
99
+ byte count, a part made by `split -b`, stray bytes, or a binary body that a log line holds. A
100
+ byte-order mark always means UTF-8. Each character that is not valid becomes U+FFFD, and
101
+ `meta.replacedCharacters` counts them.
102
+ 3. A file whose only fault is emoji written as two halves of a surrogate pair (CESU-8, as an Oracle
103
+ export in its UTF8 character set and Java's modified UTF-8 write them) is read as UTF-8, with
104
+ its emoji.
105
+ 4. Otherwise the encoding is chosen on the lines that are not UTF-8 and hold a letter (a byte of
106
+ 0xC0 or more), wherever they are in the file, up to 64 KB of them. Lines of signs alone
107
+ (– ’ € °) choose only when no line has a letter. Shift_JIS is tried on the first 64 KB of the
108
+ lines that are not UTF-8. An encoding fits when those lines read as words of its letters, with
109
+ at most one word or sign in 50 that looks wrong. The first that fits, in the order of the table,
110
+ is the one.
111
+ 5. When no line holds a UTF-8 character, the whole file is read in that encoding. Otherwise each
112
+ line that is valid UTF-8 is read as UTF-8, and the other lines in that encoding. A byte that the
113
+ encoding does not have becomes U+FFFD and is counted.
114
+ 6. When no encoding fits, the file is read as UTF-8, and its characters that are not valid are
115
+ counted.
116
+
117
+ The model is told how the file was read. The card of a large file has the line
118
+ `This file is not in UTF-8. Its text was read as windows-1255: if its letters look wrong, ask the user to save it as UTF-8.`,
119
+ which goes on ` 1 character of it was not valid in windows-1255, and shows as �.` when a byte was
120
+ not in that encoding. A file read as UTF-8 with characters that are not valid gets
121
+ `3 characters of this file were not valid UTF-8, and show as �.` A file sent whole says the same in
122
+ its first frame line, after the count of lines: `, read as windows-1255` or
123
+ `, 3 characters not valid UTF-8, shown as �`. `toDocumentSummary` passes `encoding` and
124
+ `replacedCharacters` on, so the upload route of `createDocumentHandlers` answers with them, and
125
+ your page can show "read as windows-1255".
126
+
127
+ Such a file is read in steps of about a megabyte, with pauses for other requests, and stops when
128
+ the ingest's signal aborts. Decoding a 30 MB file all in windows-1255 took 0.27 to 0.28 s, in steps
129
+ of 15 ms at most. Files with lines in both encodings take longer: 0.35 to 0.37 s for a CSV of
130
+ windows-1255 rows with one UTF-8 row, and 0.50 to 0.53 s for a log whose lines take turns between
131
+ windows-1252 and UTF-8, with one windows-1252 line more than UTF-8 lines (30 MB each; Node 24,
132
+ Windows, a shared machine). With as many lines of each, that log is read as UTF-8, by rule 2. A
133
+ valid UTF-8 file is decoded in one step, as before.
134
+
135
+ What it gets wrong, as a rule:
136
+
137
+ - **Encodings it does not recognize** are read as UTF-8, with U+FFFD and the count: Greek
138
+ (windows-1253), Turkish (windows-1254), Central European (windows-1250: Polish, Czech, Slovene),
139
+ Icelandic, KOI8-R and KOI8-U, the DOS and OEM code pages (437, 850, 866), ISO-8859-5 and
140
+ ISO-8859-6, EUC-JP, Chinese (GBK, Big5), Korean (EUC-KR) and Thai (windows-874).
141
+ - **Hungarian** in windows-1250 or ISO-8859-2 is read as windows-1252, with õ and û in place of ő
142
+ and ű: a search for a word with ő or ű finds nothing.
143
+ - **Japanese with few or no kana**, such as a list of names, cities and addresses in kanji only, is
144
+ not recognized as Shift_JIS, and is read as UTF-8 with U+FFFD.
145
+ - **ISO-8859-15** is read as windows-1252 when it has no œ: its € comes out as ¤. A file with
146
+ words such as cœur or bœuf is most often read as UTF-8 instead, with U+FFFD for every letter
147
+ that is not ASCII: in windows-1252, its œ is ½, and ½ between two letters does not fit. A file
148
+ whose only characters that are not ASCII are ₪ amounts, with no Hebrew letter, is read as
149
+ windows-1252 too, with ¤.
150
+ - **A short file can be read in a wrong encoding.** A line or two of Greek capitals comes out as
151
+ windows-1251, "Dzień dobry." as windows-1252, "Straße" saved in DOS code page 850 as
152
+ windows-1252 "Straáe", and a Thai name as windows-1256 or Shift_JIS. The rule of one line in 200
153
+ counts lines, so the same holds for a file of fewer than 200 lines, or of one long line (minified
154
+ JSON, or line ends that are a CR alone), whose few stray bytes happen to fit an encoding.
155
+ `meta.encoding` names the encoding used. A few lines of half-width katakana in Shift_JIS can be
156
+ read as UTF-8 with U+FFFD: pairs of their bytes are valid UTF-8 by chance, so some lines count as
157
+ UTF-8 (rule 1).
158
+ - **A few words the encoding does not explain** can tip a file to UTF-8 with U+FFFD, when most of
159
+ its lines that are not UTF-8 hold only signs: a Hebrew price list with a few rows such as
160
+ לGoogle, or a windows-1252 CSV with an Icelandic name or two.
161
+ - **Lines in an older encoding inside a UTF-8 file** become U+FFFD and are counted, when the file
162
+ is mostly UTF-8, or when at most one line in 200 is not UTF-8: Hebrew names in windows-1255 on
163
+ 0.4% of the lines of a log, or 10 lines with a Latin-1 "José" among 20,000.
164
+ - **Lines that are valid UTF-8 by chance**, in a file in an older encoding, are read as UTF-8: the
165
+ half-width katakana name マサヒコ in Shift_JIS comes out as ϻ˺, and Weiß’ in windows-1252 as Weiߒ.
166
+ This is rare, and most likely in a file of half-width katakana alone. In the same kind of file, a
167
+ line with a UTF-8 character and a byte that is not valid is read in the older encoding.
168
+ - **Two readings of one file.** An editor that opens a file in an older encoding as UTF-8 shows its
169
+ lines as �, while the model reads them in the older encoding. A person who checks the file there
170
+ does not see what the model reads
171
+ ([Security](../security.md#text-files-that-were-not-utf-8)). Lines that are valid UTF-8 read
172
+ the same in both.
173
+
174
+ A Node.js built without full ICU may lack these encodings; a file is then read as UTF-8, with the
175
+ count. The builds of nodejs.org have them.
176
+
177
+ When letters look wrong, or show as �, ask the user to save the file as UTF-8 and upload it again:
178
+ in Excel, Save As "CSV UTF-8 (Comma delimited)"; in Notepad, Save As with the encoding UTF-8. A
179
+ document that 0.5.0 stored from a file in one of these encodings still holds U+FFFD: upload the
180
+ file again.
181
+
182
+ ### DOCX and PPTX
183
+
184
+ - A text box is read once, after the paragraph it is anchored in. Word stores it twice, the second
185
+ time for older programs.
186
+ - A table comes out one cell per line, and an empty cell leaves no line at all, so a row with an
187
+ empty cell reads like a shorter row. PDF tables are rebuilt with their empty cells
188
+ ([PDF tables](#pdf-tables)): if those matter, the PDF of the same document reads better.
189
+ - Comments and speaker notes are not read.
190
+ - Text that Word hides (a run marked `<w:vanish/>`) is kept, after the text of its paragraph that
191
+ shows, and each of its lines starts with `[Hidden text, not shown in the document]`, so the model
192
+ can tell it from what a reader sees. A carriage return, a U+0085 or a line separator in it starts
193
+ a new marked line, and a line longer than about 1,950 characters is cut into pieces, each marked.
194
+ The text of a run inside a hidden run, such as the reading of a ruby, is marked too. The marks
195
+ count toward `maxTextBytes`.
196
+ - A slide that the slide show skips keeps its text, under
197
+ `## Slide 2 (hidden, not shown in the slide show)`.
198
+ - The mark is a hint, not a filter. Text without it can still be hidden from a reader: text hidden
199
+ through a style, a hidden shape on a slide that shows, white or 1-point text, a text box inside a
200
+ hidden run, tags written with a prefix other than `w:` or `p:`, a `show` value written as a
201
+ character reference (`show="&#48;"`), and parts that nothing in the file refers to (an orphan
202
+ header or slide). Of `mc:AlternateContent`, the `mc:Choice` is read, where Word may show the
203
+ `mc:Fallback`. And a document's own text can write the mark. A `w:val` written as a character
204
+ reference does the opposite: `<w:vanish w:val="&#48;"/>`, which Word reads as 0, marks text that
205
+ Word shows.
206
+ - Pictures are not marked, and `view_pages` works on PDFs only. For a deck of charts, the PDF
207
+ export of the deck lets the model look at the slides.
208
+
209
+ ### What is refused
210
+
211
+ `files.ingest` throws an `Error` whose message is meant for the user. `createDocumentHandlers`
212
+ answers it with HTTP 422 and that message, except a file over `maxUploadBytes`, which the upload
213
+ route refuses before reading it all: HTTP 413, `The file is larger than the 100 MB upload limit.`
214
+ ([node reference](../reference/node.md)). For a damaged or locked file the message is the reader's
215
+ own, from pdf.js or jszip, and not written for a user: an application that wants friendlier wording
216
+ maps these messages itself.
217
+
218
+ | What | Message |
219
+ |---|---|
220
+ | An empty file | `report.pdf is empty.` |
221
+ | A file over `maxUploadBytes` (100 MB by default) | `report.pdf is larger than the 100 MB upload limit.` |
222
+ | A gzip file, such as `app.log.gz` | `This file is gzip-compressed. Decompress it, then attach the text file inside.` |
223
+ | A ZIP archive, and the Office files other than DOCX and PPTX that are ZIPs inside (XLSX, for example) | `This file is a ZIP archive. Extract it, then attach the text file you need.` |
224
+ | Any other binary file: images, legacy `.doc` and `.xls` | `This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.` |
225
+ | A file that holds no text once read | `report.docx did not contain any text.` |
226
+ | A DOCX or PPTX that unpacks to more than 100 times its size (past the first 16 MB), or to more than 128 MB of XML | `This DOCX unpacks to more than …`, which ends `Save it as text or PDF, and attach that.` |
227
+ | A PDF of more than `maxPdfPages` pages (5,000 by default), before any page is read | `This PDF has 6,200 pages, more than the 5,000 read from one file. Split it, and attach the part you need.` |
228
+ | A PDF whose text passes `maxTextBytes` (100 MB by default, or `maxUploadBytes` when that is larger), counted page by page | `This PDF holds more than 100 MB of text, more than is kept from one file. Split it, and attach the part you need.` |
229
+ | A PDF whose page tree lists one page more than once | `This PDF lists the same page more than once. A file built that way can hold far more text than its size, so it is not read. Print it to a new PDF, and attach that.` |
230
+ | A PDF whose pages draw more than 100 times its size in text (past the first 16 MB), by painting forms inside forms | `This PDF draws more than 16 MB of text, over 100 times its size. A file that grows that much is not read: it may be built to exhaust the server.` |
231
+ | A PDF with a page that would hold the server while pdf.js reads it, found before any page is read (with `@cantoo/pdf-lib`; [Pages that would hold the server](#pages-that-would-hold-the-server)) | `Page 1 of this PDF draws far more than its file holds, and reading it would hold the server for a long time. A file built that way is not read: it may be built to exhaust the server. Print it to a new PDF, and attach that.` |
232
+ | A PDF whose pages are each within that limit, but together far past it | `This PDF draws far more than its file holds, and reading it would hold the server for a long time. A file built that way is not read: it may be built to exhaust the server. Print it to a new PDF, and attach that.` |
233
+ | A PDF with a page whose content is stored with a filter that only images use (JPEG, JPEG 2000, JBIG2, CCITT), or decodes to more than 64 MB through LZW, ASCII85, ASCIIHex or RunLength | `Page 1 of this PDF stores its content in a way that cannot be checked before it is read, so it is not read. Print it to a new PDF, and attach that.` |
234
+ | A DOCX or PPTX of more than 32 million characters of text | `This DOCX holds more than 32 million characters of text, more than is read from one file. Split it, and attach the part you need.` |
235
+ | A DOCX or PPTX whose text passes `maxTextBytes`, when that is below 32 million | `This DOCX holds more than 10 MB of text, more than is kept from one file. Split it, and attach the part you need.` |
236
+ | A DOCX or PPTX of more than 1,000,000 paragraphs with text | `This DOCX has more than 1,000,000 paragraphs, more than a document holds. It may be built to exhaust the server, so it is not read.` |
237
+ | A DOCX or PPTX with paragraphs nested more than 32 deep | `This DOCX nests paragraphs more than 32 deep, which no document does. It may be built to exhaust the server, so it is not read.` |
238
+ | A DOCX or PPTX of more than 20,000 parts, counted the way JSZip will read them, whatever count the file gives | `This DOCX has more than 20,000 parts, more than an Office document has. It may be built to exhaust the server, so it is not read.` |
239
+ | A DOCX or PPTX with more than 80,000 extra fields, or more than 8 MB of names, comments and extra-field data that JSZip would turn into text or go through byte by byte | `This DOCX lists its parts in a way that no Office program does: reading the list would take far more memory or time than an Office document needs. It may be built to exhaust the server, so it is not read.` |
240
+ | A DOCX or PPTX whose ZIP64 end record says it is longer than its fields, which JSZip would read in a loop without end | `This DOCX ends with a ZIP64 record that cannot be read, and reading it could hold the server without end. It may be built to exhaust the server, so it is not read.` |
241
+ | A file of any format whose text, from an extractor of your own or the text extractor, passes `maxTextBytes` | `notes.txt holds more than 100 MB of text, more than is kept from one file. Split it, and attach the part you need.` |
242
+ | 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.` |
243
+ | A PDF without text on any page | See [Scanned PDFs](#scanned-pdfs). |
244
+ | A PDF that needs a password to open | `No password given`, the message of pdf.js. |
245
+ | A damaged PDF | The message of pdf.js, such as `Invalid PDF structure.` |
246
+ | A damaged DOCX or PPTX, 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 ? …` |
247
+ | A DOCX without `word/document.xml` | `This DOCX does not contain word/document.xml.` |
248
+ | A PPTX without slides | `This PPTX does not contain any slides.` |
249
+ | A DOCX or PPTX without `jszip` installed | `Reading DOCX and PPTX files needs the optional dependency "jszip".` |
250
+ | A PDF without `unpdf` installed | `Reading PDF files needs the optional dependency "unpdf".` |
251
+ | 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.` |
252
+ | 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.` |
253
+ | 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`. |
254
+
255
+ A missing dependency, or an `unpdf` that does not run on your Node, is your server's fault, but it
256
+ reaches the user as a 422, a file that cannot be read. Install the dependencies wherever the upload
257
+ route runs, in versions that run on its Node ([Formats](#formats)). The messages name the major
258
+ version of Node only.
259
+
260
+ The numbers in the messages are your limits: `maxPdfPages`, `maxTextBytes` and `ingestTimeoutMs`
261
+ of `createLargeFiles` ([`LargeFilesOptions`](../reference/library.md#largefilesoptions)). A size
262
+ below 1 MB is given in KB, and below 1 KB in B; a time below a second in ms, below 2 minutes in s,
263
+ and from there in min. An Office message says `PPTX` for a presentation. An Office file is
264
+ refused past 32 million characters of text even when `maxTextBytes` is larger. The ZIP directory
265
+ of a DOCX or PPTX is read before JSZip reads it, the way JSZip will read it, record by record:
266
+ the count of parts that the file gives is not used, and the parts are not counted past 20,000
267
+ ([Security](../security.md#uploads)).
268
+
269
+ What the user can do:
270
+
271
+ - **A long PDF, or one with a lot of text:** split it (by chapters, by year), and attach the part
272
+ the question is about. If such files are expected, raise `maxPdfPages` or `maxTextBytes`; the
273
+ text is then searched as any other.
274
+ - **A file that took too long:** split it, or save it again as plain text (or, for a PDF, print it
275
+ to a new PDF), and attach that. A server that is busy reads slower: if files that should pass
276
+ are refused, raise `ingestTimeoutMs`, and check how many ingests run at once
277
+ ([Deployment](./deployment.md#uploads-and-ingest)).
278
+ - **A PDF that lists a page more than once, or an Office file that nests, repeats or splits its
279
+ content past what a program writes:** these are built to exhaust a server, not written by Word,
280
+ PowerPoint or a PDF printer. If one comes from a real program, opening it there and saving it
281
+ again, or printing it to a new PDF, writes it the usual way.
282
+ - **A PDF with a page that would hold the server:** the same. If your users' real files are
283
+ refused this way, `createPdfExtractor({ checkPages: false })` reads them, and every page then
284
+ takes as long as pdf.js needs (below).
285
+
286
+ ### Pages that would hold the server
287
+
288
+ pdf.js reads the text of a page in one block: until it is done, no other request on the server is
289
+ answered, and neither `ingestTimeoutMs` nor a signal stops it. A page of a document takes a few
290
+ milliseconds. A page built to paint a form that paints another form, many times over, held the
291
+ server for 13 s to 2 minutes, from files of 2 to 21 KB
292
+ ([measured](../measurements.md#the-server)).
293
+
294
+ With `@cantoo/pdf-lib` installed, the PDF extractor adds up what each page would make pdf.js run,
295
+ before pdf.js reads any page:
296
+
297
+ - the content of the page;
298
+ - each form the content paints, every time it is painted, with what the form paints in turn. pdf.js
299
+ runs a form without text once, and skips its other paints: so does the count;
300
+ - the first time the file sets a font: its font program and maps, and every glyph program of a
301
+ Type3 font, with the forms, patterns and shadings it paints. pdf.js does not decode an image to
302
+ read text, so images count for nothing.
303
+
304
+ It reads the file without running it, and counts high where it cannot tell: any name written
305
+ before a paint may be the drawing painted, and anything that looks like a text operator makes a
306
+ form one with text. A byte of content counts one unit, a form painted for its text 640 more
307
+ (about 0.1 ms of pdf.js, which took 75 to 85 µs), and a form painted by a glyph 256 more. A page is
308
+ refused past 8,388,608 units, about 1 to 1.5 s of pdf.js, or past 32 times the size of the file
309
+ when that is more, and a file whose pages add up to more than four times that. What the check
310
+ looks through counts against that file budget too, 16 units for each entry of a resource
311
+ dictionary, so a file cannot make the check itself work long. The pages of the real documents
312
+ tested ran up to 11% of their limit. The count follows pdf.js 5.4, the version `unpdf` 1.4
313
+ bundles, and its cost was measured with that version only. Later versions of `unpdf` bundle pdf.js
314
+ 5.6 (1.5 to 1.7), 6.1 (1.8), 6.4 (1.9 to 2.1) and 6.5 (2.2): what a page costs them was not
315
+ measured, and may be more.
316
+
317
+ What still holds the server while pdf.js reads a page:
318
+
319
+ - a page within the limit: up to about 1.5 s in a small file, and longer in a large one (a page of
320
+ a 10 MB file may run 320 MB of content);
321
+ - any page, when `@cantoo/pdf-lib` is not installed or cannot read the file, when the file
322
+ declares more than 150,000 objects, or with `checkPages: false`;
323
+ - a file built to be read one way by `@cantoo/pdf-lib` and another way by pdf.js.
324
+
325
+ Neither check looks at the memory an object takes. Both libraries build each object of the file in
326
+ one step: `@cantoo/pdf-lib` every object, and pdf.js the ones a page needs and every object of an
327
+ object stream it opens, such as the one that holds the catalog. A crafted object can take far more
328
+ heap than file: one array of one-digit numbers in a PDF of 16 MB ran a heap of 256 MB out of memory
329
+ at ingest, and 8 MB of empty dictionaries, packed with the catalog into an object stream unpacked
330
+ twice, ran a heap of 512 MB out of memory in pdf.js alone, with `checkPages: false` and
331
+ `pictures: false`, from a PDF of 759 bytes. What a stream unpacks to is held outside the heap: a PDF
332
+ of 1.6 KB whose object stream unpacks to 512 MB took 1.6 GB of memory with 20 MB of heap, and held
333
+ the server 6.1 to 6.4 s ([Security](../security.md#uploads)). Such files are not refused.
334
+
335
+ For uploads you do not trust, ingest in a process of its own, with a memory limit of its own as
336
+ well as a heap limit ([Deployment](./deployment.md#uploads-and-ingest)): only that process waits,
337
+ it can be stopped, and when it runs out of memory it stops alone.
338
+
339
+ ## PDF text
340
+
341
+ The PDF extractor reads the text with `unpdf` (pdf.js) and writes each page under a line of its own.
342
+ Pages are separated by a blank line:
343
+
344
+ ```text
345
+ --- Page 12 ---
346
+ [Picture on this page. This text cannot show it.]
347
+ Figure 3: sales by region.
348
+ | Region | Q1 | Q2 | Q3 | Q4 |
349
+ | EMEA | 80 | | 95 | 101 |
350
+ ```
351
+
352
+ - `--- Page N ---` starts every page, counting from 1. The model passes these numbers to
353
+ `view_pages`.
354
+ - A page with no text at all is written as
355
+ `[No text on this page. It may be a scan, a photo, or a chart.]`, so the model can say that it
356
+ cannot see it instead of guessing.
357
+ - With `@cantoo/pdf-lib` installed, a page that shows a picture or a drawing gets the second line
358
+ ([The line that marks a page](#the-line-that-marks-a-page)).
359
+ - Tables are rebuilt as rows of cells ([PDF tables](#pdf-tables)).
360
+
361
+ ### PDF tables
362
+
363
+ A PDF stores no tables, only text at positions. Read in file order, a row with an empty cell looks
364
+ like a row without that column: `EMEA 80 95 101` under the headings `Q1 Q2 Q3 Q4`, and a model reads
365
+ 95 as Q2. The PDF extractor finds tables by the position of their text and writes each row with its
366
+ cells marked, so the same row becomes `| EMEA | 80 | | 95 | 101 |`. In a live test of 110
367
+ questions about single cells, half of them empty, the text in file order gave 44 right answers and
368
+ the rebuilt rows 110 ([measurements](../measurements.md)).
369
+
370
+ What it handles: empty cells, tables inside one column of a two-column page, right-to-left tables
371
+ (the first column is the rightmost), tables printed sideways, rotated pages, footnote marks,
372
+ headings that span columns, and cells whose text wraps onto several lines when the rows are visibly
373
+ spaced apart. Text that is not a table (paragraphs, lists, columns of prose, justified text) is left
374
+ as pdf.js gives it.
375
+
376
+ It is cautious: where the evidence for a table is weak, the text stays as it was. So:
377
+
378
+ - A table needs three columns. Two-column tables (key and value, a glossary) stay lines of text,
379
+ which read correctly that way.
380
+ - When a cell wraps and the rows have no extra space between them, each line of the cell is a row
381
+ of its own, with the other cells empty.
382
+ - Columns that are closer together than a word space on every line of the table stay together in
383
+ one cell, on every row alike.
384
+ - A table whose text is stored column by column in the file is not rebuilt.
385
+ - Pictures and charts are not in the text. See [Pictures in PDFs](#pictures-in-pdfs).
386
+
387
+ The cell marks cost about one token per cell. The rules were tuned on PDFs made by Chrome and by
388
+ Word. To turn them off and get the text in the order pdf.js gives it, as version 0.1.0 read it,
389
+ replace the PDF extractor with one made by `createPdfExtractor`:
390
+
391
+ ```ts
392
+ import { createLargeFiles, createPdfExtractor, FileDocumentStore } from "llm-large-files";
393
+
394
+ export const files = createLargeFiles({
395
+ store: new FileDocumentStore("./data/large-files"),
396
+ // Text in pdf.js order, without rebuilt tables, and without picture marks.
397
+ extractors: { pdf: createPdfExtractor({ tables: false, pictures: false }) },
398
+ });
399
+ ```
400
+
401
+ `tables: false` alone still writes the page lines, the line for a page without text, and the
402
+ picture marks. `pictures: false` leaves out the picture marks. `checkPages: false` turns off the
403
+ check of [pages that would hold the server](#pages-that-would-hold-the-server), which changes no
404
+ text. All three default to `true`
405
+ ([`PdfExtractorOptions`](../reference/library.md#pdfextractoroptions)). With `pictures: false`
406
+ alone, `@cantoo/pdf-lib` still reads each PDF at ingest, for the page check, and the first PDF of a
407
+ process loads it, in one block of about 0.4 s. With `pictures: false` and `checkPages: false`,
408
+ ingest does not use it at all ([Deployment](./deployment.md#uploads-and-ingest)).
409
+
410
+ ## Pictures in PDFs
411
+
412
+ The text of a PDF does not hold its photos, charts and diagrams. Asked about a bar chart from the
413
+ text alone, a model can only say that it cannot see it, or guess. Two things, both for PDFs only,
414
+ close that gap:
415
+
416
+ 1. **A line in the text that says where the pictures are.** It needs `@cantoo/pdf-lib`.
417
+ 2. **A tool, `view_pages`, that hands the model the real pages** as a small PDF, when it asks. It
418
+ needs `@cantoo/pdf-lib` and the uploaded file itself, which the store keeps when you list
419
+ `"pdf"` in `keepOriginals`.
420
+
421
+ ```ts
422
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
423
+
424
+ export const files = createLargeFiles({
425
+ store: new FileDocumentStore(process.env.LARGE_FILES_DIR ?? "./data/large-files"),
426
+ // view_pages cuts pages out of the uploaded file, so the store keeps it next to the text.
427
+ keepOriginals: ["pdf"],
428
+ });
429
+ ```
430
+
431
+ Nothing else changes in your code. `askGemini` and `askWithFiles` offer `view_pages` by themselves
432
+ for every PDF whose file is kept, when the model can be sent a file
433
+ ([Which models can see pages](#which-models-can-see-pages)). A kept file takes disk space, up to
434
+ `maxUploadBytes`, until the document expires: [Storage](./storage.md) covers originals in your own
435
+ store, and [Security](../security.md) what to weigh before you keep them.
436
+
437
+ The options of this page, and where each is explained:
438
+
439
+ | Option | Default | What it does |
440
+ |---|---|---|
441
+ | `keepOriginals` (`createLargeFiles`) | `[]`: no file kept | List `"pdf"` to keep the uploaded file, which `view_pages` and scanned PDFs need ([above](#pictures-in-pdfs)). |
442
+ | `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)). |
443
+ | `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)). |
444
+ | `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)). |
445
+ | `viewPages` (`askGemini`, `askWithFiles`) | `true` | Offer `view_pages` for the PDFs whose file is kept ([Limits and cost](#limits-and-cost)). |
446
+ | `toolFilePlacement` (`gemini()`, `askGemini`, `anthropic()`) | `"inside"` | Where the pages go in the request ([Where the pages go](#where-the-pages-go-toolfileplacement)). |
447
+ | `pdfInput` (`openAiCompatible()`) | `false` | Send the pages as a `file` part; without it, no `view_pages` ([Which models can see pages](#which-models-can-see-pages)). |
448
+ | `pageTokens` (`gemini()`, `openAiCompatible()`, `anthropic()`) | 530, 1,000, 3,500 | What a page costs in input tokens ([Limits and cost](#limits-and-cost)). |
449
+
450
+ A PDF small enough to send whole can also go to the model as a file in your own message, in the
451
+ provider's own form ([Conversations](./conversations.md)). The model then sees every page.
452
+ `view_pages` is for the PDFs that are too large for that.
453
+
454
+ ### The line that marks a page
455
+
456
+ At ingest, a page that shows a picture or a drawing gets one line under its header:
457
+
458
+ ```text
459
+ --- Page 12 ---
460
+ [Picture on this page. This text cannot show it.]
461
+ Figure 3: sales by region.
462
+ ```
463
+
464
+ The words hold whether or not the model can look at the page later. A search for
465
+ `[Picture on this page` lists every such page.
466
+
467
+ What counts:
468
+
469
+ - **A picture:** the images on the page cover 3% of it or more, measured by the size they are shown
470
+ at, not by their pixels. A logo covers about 1%. An image that is on 30% of the pages (and on
471
+ three at least) is taken for a logo, a letterhead or a watermark, and does not count, whatever its
472
+ size.
473
+ - **A drawing:** shapes filled in three or more colours, outside the tables. Greys, rules, dots and
474
+ page backgrounds do not count, and neither does the shading of a table's cells.
475
+ - **A page that paints too much to be text:** drawing instructions larger than 2 MB (a map, a
476
+ technical drawing), more than 20,000 images, or more than 16 MB of instructions once each form (a
477
+ drawing kept apart and painted by name) is counted every time it is painted. Reading such a page
478
+ stops there, so forms painted inside forms cannot hold the server.
479
+
480
+ What it gets wrong:
481
+
482
+ - Missed: a chart in one or two colours, and a chart or diagram drawn only with lines.
483
+ - Marked by mistake: a table with cells shaded in three colours, when the table itself was not
484
+ recognised (a table of two columns, for example).
485
+
486
+ The mark is a hint. `view_pages` works on any page, marked or not, and the model is told to look
487
+ when a page mentions a figure too.
488
+
489
+ The pages are found from the structure of the file, without decoding any image, so it is cheap
490
+ ([measurements](../measurements.md)). No page is marked, and the text is exactly that of version
491
+ 0.2.0, when:
492
+
493
+ - `@cantoo/pdf-lib` is not installed;
494
+ - you turn it off with `createPdfExtractor({ pictures: false })`;
495
+ - the file declares more than 150,000 objects (reading it would take over two seconds), or more
496
+ than about 60% of the free heap can hold;
497
+ - finding the pictures, once the file is read, took more than five seconds;
498
+ - `@cantoo/pdf-lib` cannot read the file;
499
+ - `@cantoo/pdf-lib` counts other pages than the text extractor did.
500
+
501
+ ### `view_pages`
502
+
503
+ `view_pages(document_id, from_page, to_page)` cuts those pages out of the kept file and returns them
504
+ as one PDF, which goes to the model with the tool result. The model reads it like any PDF: text,
505
+ pictures and layout. `to_page` defaults to `from_page`. The result says what was shown:
506
+
507
+ ```json
508
+ { "document": "report.pdf", "pages": "12-14", "total_pages": 40, "file": "pages-12-14.pdf" }
509
+ ```
510
+
511
+ When fewer pages were shown than asked, it has a `note` that says why, and `next_page` where to go
512
+ on, unless the pages the question may show ran out. The exact results and errors are in the
513
+ [tools reference](../reference/tools.md).
514
+
515
+ What the model is told:
516
+
517
+ - The system instruction lists the PDFs it can look at, with their page counts, and tells it to
518
+ look when the answer depends on a picture, a chart, a diagram, a map, handwriting, a stamp or the
519
+ layout, and not to use the tool to read text.
520
+ - The card of a searched PDF says that its text cannot show pictures.
521
+ - Search and read results of such a PDF say which page a line is on (`"page": 12` for a match,
522
+ `"pages": "12-14"` for a passage or a read), since a page number is what `view_pages` takes.
523
+
524
+ It is offered for every PDF whose file is kept, also for one whose text is already in the prompt: a
525
+ slide deck of photos has little text, so its text fits, and without the tool the model would see
526
+ none of its slides. Such a PDF gets `view_pages` and no search tools.
527
+
528
+ A look shows up in your steps and in the result:
529
+
530
+ ```ts
531
+ import { GoogleAuth } from "google-auth-library";
532
+ import { askGemini, vertexAi } from "llm-large-files/gemini";
533
+
534
+ // files: the library above. reportId: the ID that files.ingest returned. userId: who asks.
535
+ const auth = new GoogleAuth({ scopes: ["https://www.googleapis.com/auth/cloud-platform"] });
536
+ const endpoint = vertexAi({
537
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
538
+ location: "global",
539
+ model: "gemini-3.5-flash-lite",
540
+ accessToken: async () => (await auth.getAccessToken()) ?? "",
541
+ });
542
+
543
+ const result = await askGemini({
544
+ files,
545
+ endpoint,
546
+ owner: userId,
547
+ documentIds: [reportId],
548
+ messages: [{ role: "user", text: "Which region has the tallest bar in the chart on page 12?" }],
549
+ onStep: (step) => console.log(step), // "Look at report.pdf page 12"
550
+ });
551
+
552
+ // The pages the model looked at, for a list of sources under the answer.
553
+ const looked = result.evidence.filter((item) => item.tool === "view_pages");
554
+ ```
555
+
556
+ A cut holds the pages asked for and little else. Copied the simple way, a contents page brings
557
+ along every page it links to. Here every other page is set to null before copying, and a page that
558
+ shares one list of images with the whole file (FPDF, TCPDF and jsPDF write PDFs that way) gets a
559
+ list of its own. Hidden layers stay hidden, rotated pages and links are kept, and a PDF encrypted
560
+ only to restrict printing or copying opens without a password. The cut is not encrypted.
561
+
562
+ Pages that cannot be shown get an error result, and the model answers from the text:
563
+
564
+ | Case | The model is told |
565
+ |---|---|
566
+ | `@cantoo/pdf-lib` is not installed | `report.pdf: Showing PDF pages needs the optional dependency "@cantoo/pdf-lib".` |
567
+ | The PDF needs a password to open | `report.pdf: This PDF needs a password to open, so its pages cannot be shown.` |
568
+ | The file is damaged | `report.pdf: This PDF could not be read to cut pages from it. It may be damaged.` |
569
+ | `@cantoo/pdf-lib` counts other pages than the text has | `report.pdf: The pages of this PDF could not be matched to its text (41 pages against 40), so they cannot be shown.` |
570
+ | The file declares more than 1,000,000 objects, or more than about 60% of the free memory can hold | `report.pdf: This PDF has 1,200,000 objects, too many to cut pages from it in memory.` |
571
+ | A page past the end | `report.pdf has 40 pages. There is no page 41.` |
572
+
573
+ What a look costs the server: the whole file is read into memory for every call. At the peak that
574
+ is about twice the size of the file, plus 1 to 1.6 KB for each object in it. A file built to
575
+ exhaust the server can take far more, because each object is built in one step and nothing checks
576
+ it before: a look at a PDF of 8 MB that is one array of one-digit numbers took 422 to 427 MB of
577
+ heap, and ran a heap of 256 MB (`--max-old-space-size=256`) out of memory; one of 16 MB ran a heap
578
+ of 512 MB out of memory, and took 984 MB on a heap of 2 GB. A look takes more than the ingest of
579
+ the same file did (232 to 244 MB for that 8 MB file), so a file that a process of its own ingested
580
+ can still stop the server that answers the question. What a stream unpacks to is outside the heap:
581
+ a look at a PDF of 1.6 KB whose object stream unpacks to 512 MB took 1.1 GB of the server's
582
+ memory. The check on the number of objects does not see such files, which declare few, and what
583
+ `@cantoo/pdf-lib` keeps after each look adds up from file to file
584
+ ([Security](../security.md#reading-pdfs-for-pages-and-pictures)). For the documents of users you
585
+ do not trust, do not offer `view_pages` (`viewPages: false`), or keep no PDF originals. Peak memory
586
+ for real files is in [measurements](../measurements.md); [Deployment](./deployment.md) sizes
587
+ servers for it.
588
+
589
+ A look parses the file, copies the pages and writes the cut. It pauses after every 12 ms of that
590
+ work so that other requests get a turn, or after up to 40 ms where a pause itself takes long, as a
591
+ timer does on Windows. It cannot be stopped once it has started. Measured on Windows with Node 24,
592
+ a look at three pages of a 2,000-page PDF of 6.2 MB held the server for about 20 ms at a time
593
+ (19 to 48 ms on a busy machine), where 0.5.0 held it 159 to 177 ms. Some steps still run in one
594
+ block:
595
+
596
+ - one object of the file: about 0.1 to 0.35 s for each MB, by what it holds, and about 0.03 s for
597
+ each MB of a stream whose length the file gives by reference. A crafted PDF of 16 MB with one
598
+ array of numbers such as `1234.5` held the server 1.6 to 2.7 s at ingest and 1.7 to 2.5 s on each
599
+ look, and 2.7 to 3.5 s on each look when its numbers were of one digit, on a heap that could hold
600
+ it (that look took 984 MB);
601
+ - a stream unpacked to reach an object: 1.0 s for an object stream that unpacks to 512 MB;
602
+ - a cross-reference stream inside the file that declares many objects: 0.7 s for a million;
603
+ - a cross-reference table written as text: 0.15 s for 150,000 objects;
604
+ - the first look of a process, which loads `@cantoo/pdf-lib`: about 0.4 s, unless the
605
+ server loads it when it starts ([Deployment](./deployment.md#uploads-and-ingest)).
606
+
607
+ A look runs on the server that answers the question, not where the file was ingested
608
+ ([Deployment](./deployment.md#pages-of-pdfs)).
609
+
610
+ ### Limits and cost
611
+
612
+ | Limit | Value | When it is reached |
613
+ |---|---|---|
614
+ | Pages per call | 5 (`MAX_VIEW_PAGES`) | The result has `next_page`, and a note that says to call again from there. |
615
+ | Bytes per call | What is left of `maxRequestBytes`, less a tenth kept free (256 KB at least), times 3/4 for base64 | Pages are left off the end of the call. A first page that does not fit by itself is an error, and the model answers from what it has. |
616
+ | Pages per question | Half of `reservedTokens`, divided by what a page costs: 60 on Gemini, 32 on an OpenAI-compatible model with `pdfInput`, 12 on Claude, with the default budget | `No more pages can be looked at for this question. Answer from the pages and the text you already have.` |
617
+
618
+ What a page costs is what the adapter declares as `pageTokens`, in input tokens: 530 for `gemini()`
619
+ (Gemini bills 520 to 532 a page, whatever is on it), 1,000 for `openAiCompatible()`, and 3,500 for
620
+ `anthropic()`, a page's text and its picture, which the loop counts at Claude's `tokenScale` of 1.35.
621
+ Set `pageTokens` on the adapter (`gemini(endpoint, { pageTokens })`, `openAiCompatible({ pageTokens })`,
622
+ `anthropic({ pageTokens })`) when your model bills otherwise. `askGemini` has no such option: use
623
+ `askWithFiles` with `gemini()` for that. A smaller window means a smaller
624
+ `reservedTokens`, and fewer pages: [Costs and limits](./costs-and-limits.md) explains the budget.
625
+
626
+ Pages stay in the request until the question is answered, so every look makes each later request of
627
+ that question larger, and each of them bills the pages again. Only when the request runs short of
628
+ room are the older tool rounds, pages included, replaced by short stand-ins that say the pages are
629
+ no longer attached; when Claude takes part in the question, they never are ([How it works](../how-it-works.md)). Pages are not
630
+ sent with the next question: `toolTurns` keep only that the pages were shown. Turn the tool off for
631
+ one question with `viewPages: false` on `askGemini` or `askWithFiles`.
632
+
633
+ ### Which models can see pages
634
+
635
+ The pages are a file. A model that cannot be sent one in a tool result does not get `view_pages`,
636
+ and with an [explorer model](./explorer-model.md), both models must be able to take it: the
637
+ answering model reads the same pages.
638
+
639
+ | Adapter | How the pages are sent | Setting | `pageTokens` |
640
+ |---|---|---|---|
641
+ | `gemini()`, `askGemini` | Inside the function response (default), or in a user turn after it | `toolFilePlacement`: `"inside"` or `"beside"` | 530 |
642
+ | `anthropic()` | A `document` block inside the `tool_result` (default), or after the tool results in the same user turn, or not at all | `toolFilePlacement`: `"inside"`, `"beside"` or `"none"` | 3,500 |
643
+ | `openAiCompatible()` | Not at all (default), or a `file` part in a user message after the tool messages | `pdfInput: true` | 1,000 |
644
+ | An adapter of your own | As its `capabilities.toolFiles` says | `"inside"`, `"beside"` or `"none"` | `capabilities.pageTokens` |
645
+
646
+ ```ts
647
+ import { askWithFiles } from "llm-large-files";
648
+ import { anthropic } from "llm-large-files/anthropic";
649
+ import { gemini, vertexAi } from "llm-large-files/gemini";
650
+ import { openAiCompatible } from "llm-large-files/openai";
651
+
652
+ // auth, files, reportId and userId as above. Any of the three adapters below can be the model
653
+ // (or the explorer): view_pages is offered for each.
654
+ // Gemini 2.5 does not see a file inside a function response: send the pages beside it.
655
+ const gemini25 = gemini(
656
+ vertexAi({
657
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
658
+ model: "gemini-2.5-flash-lite",
659
+ accessToken: async () => (await auth.getAccessToken()) ?? "",
660
+ }),
661
+ { toolFilePlacement: "beside" },
662
+ );
663
+
664
+ // Claude: the pages go inside the tool result by default. "none" takes view_pages away.
665
+ const claude = anthropic({ model: "claude-opus-5-5", apiKey: process.env.ANTHROPIC_API_KEY! });
666
+
667
+ // An OpenAI-compatible model that reads PDF input. Without pdfInput, view_pages is not offered.
668
+ const gpt = openAiCompatible({
669
+ model: process.env.OPENAI_MODEL!,
670
+ apiKey: process.env.OPENAI_API_KEY!,
671
+ pdfInput: true,
672
+ });
673
+
674
+ // Here Claude answers; gemini25 or gpt in its place works the same way.
675
+ const answer = await askWithFiles({
676
+ files,
677
+ model: claude,
678
+ owner: userId,
679
+ documentIds: [reportId],
680
+ messages: [{ role: "user", text: "What does the stamp on the last page say?" }],
681
+ });
682
+ ```
683
+
684
+ `pdfInput` is off by default because many servers behind the OpenAI API take no PDF at all, and a
685
+ tool message holds text only. Gemini's own OpenAI-compatible endpoint refuses the `file` part with
686
+ HTTP 400: use `gemini()` for Gemini. The page parts of `anthropic()` and of `pdfInput` follow the
687
+ request shapes of the providers' documentation; [measurements](../measurements.md) lists what has
688
+ been run live. The provider guides cover the rest of each setup: [Vertex AI and
689
+ Gemini](./vertex-and-gemini.md), [Claude](./anthropic.md), [OpenAI-compatible
690
+ endpoints](./openai-compatible.md).
691
+
692
+ ### Where the pages go: `toolFilePlacement`
693
+
694
+ On Gemini:
695
+
696
+ | `toolFilePlacement` | What is sent | Gemini 3.5 Flash-Lite, Gemini API and Vertex AI | Gemini 2.5 Flash-Lite, Vertex AI |
697
+ |---|---|---|---|
698
+ | `"inside"` (default) | The PDF in the `parts` of its function response, which names it as `{ "$ref": "pages-12-14.pdf" }` | Works | Accepted and billed, but the model does not see the pages |
699
+ | `"beside"` | The function responses in one `user` turn, then the PDFs in a `user` turn of their own, each after a line that names it | Works | Works |
700
+
701
+ The table is from live checks ([measurements](../measurements.md)). Keep the default for Gemini 3
702
+ models, and use `"beside"` for Gemini 2.5: it takes a file inside a function response without an
703
+ error, bills its tokens, and then answers that it cannot see the page. For another model, ask it
704
+ once about a chart and check that it reads it.
705
+
706
+ With `"beside"`, the files get a turn of their own because Vertex AI refuses a turn in which anything
707
+ follows a function response (HTTP 400). `askGemini` takes the option for the model and its explorer
708
+ together:
709
+
710
+ ```ts
711
+ import { askGemini, vertexAi } from "llm-large-files/gemini";
712
+
713
+ // auth, files, reportId and userId as above.
714
+ const result25 = await askGemini({
715
+ files,
716
+ endpoint: vertexAi({
717
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
718
+ model: "gemini-2.5-flash-lite",
719
+ accessToken: async () => (await auth.getAccessToken()) ?? "",
720
+ }),
721
+ owner: userId,
722
+ documentIds: [reportId],
723
+ messages: [{ role: "user", text: "What does the chart on page 3 show?" }],
724
+ toolFilePlacement: "beside",
725
+ });
726
+ ```
727
+
728
+ On Claude, `"inside"` puts a `document` block in the `tool_result` itself, and `"beside"` puts the
729
+ blocks after all the tool results of the turn, each after a line that names it: the Messages API
730
+ refuses text before a tool result.
731
+
732
+ ### When `view_pages` is missing
733
+
734
+ The model gets `view_pages` for a PDF only when all of these hold:
735
+
736
+ - `keepOriginals` lists `"pdf"`, and the store has `putOriginal` and `getOriginal`.
737
+ `FileDocumentStore` and `MemoryDocumentStore` have both. Documents ingested before you turned it
738
+ on have no file kept: upload them again. `meta.originalKept` says whether a document has one.
739
+ - Every model of the question can be sent a file: not `openAiCompatible()` without `pdfInput`, not
740
+ `anthropic({ toolFilePlacement: "none" })`.
741
+ - The question does not set `viewPages: false`.
742
+ - In a loop of your own, you asked for it ([Your own tool loop](#your-own-tool-loop)).
743
+
744
+ The tool is offered without `@cantoo/pdf-lib` too, and then every call answers with the error above:
745
+ install it. If the tool is offered and the model never calls it, the text may be enough. In a live
746
+ test, ten questions that the text answers led to no look at all ([measurements](../measurements.md)).
747
+ [Troubleshooting](../troubleshooting.md) has more symptoms.
748
+
749
+ ## Scanned PDFs
750
+
751
+ A PDF without text on any page (a scan, or pages of photos) has nothing to search. When its file is
752
+ not kept, it is refused at ingest:
753
+
754
+ ```text
755
+ This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.
756
+ ```
757
+
758
+ When its file is kept, the model can read it by looking at its pages, so a scan of up to
759
+ `scannedPdfPages` pages is accepted. Each page of its text is its `--- Page N ---` line and the line
760
+ for a page without text (with `@cantoo/pdf-lib`, the picture line too). That text is short, so it
761
+ usually goes into the prompt whole, and the model gets `view_pages` and no search tools. A longer
762
+ scan is refused:
763
+
764
+ ```text
765
+ This PDF has no text layer (it may be scanned) and 31 pages. Without text it can only be read by looking at its pages, which works for up to 30 pages. It needs OCR first.
766
+ ```
767
+
768
+ ```ts
769
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
770
+
771
+ export const files = createLargeFiles({
772
+ store: new FileDocumentStore("./data/large-files"),
773
+ keepOriginals: ["pdf"], // without it, every scan is refused
774
+ scannedPdfPages: 30, // the default. 0 refuses every scan.
775
+ });
776
+ ```
777
+
778
+ `scannedPdfPages` has an effect only when PDFs are kept, by a store that can keep them. A PDF with
779
+ text on any page is always accepted, however many of its pages are scans: those pages say that they
780
+ have no text, and with the file kept the model can look at them.
781
+
782
+ Raising `scannedPdfPages` lets longer scans in, but the model still reads them five pages a call,
783
+ within the pages a question may show ([Limits and cost](#limits-and-cost)) and its tool turns, and
784
+ nothing in them can be searched. A long scan needs text: OCR it, at ingest or before
785
+ ([OCR](#ocr)).
786
+
787
+ ## Custom extractors
788
+
789
+ An extractor turns the bytes of one format into text:
790
+ `(bytes, input) => Promise<{ text: string; pages?: number }>`. `input` has the file's `name`, its
791
+ `mimeType` and its `format`, and for a PDF, `scannedPages` ([below](#rules-for-a-pdf-extractor)).
792
+ Pass yours in `extractors`, by format. The other formats keep the built-in extractors, which
793
+ `defaultExtractors` holds, one per format ([`Extractor`](../reference/library.md#extractor),
794
+ [`defaultExtractors`](../reference/library.md#defaultextractors)).
795
+
796
+ `input` also carries the limits of the ingest, for your extractor to honour
797
+ ([`ExtractInput`](../reference/library.md#extractinput)):
798
+
799
+ | Field | What it is | What to do with it |
800
+ |---|---|---|
801
+ | `signal` | Aborted after `ingestTimeoutMs` (2 minutes by default), or when the caller's `IngestInput.signal` aborts. Its `reason` is the error to throw. | Pass it to the work you start (`fetch(url, { signal: input.signal })`), and call `input.signal?.throwIfAborted()` between long steps. When it aborts, `ingest` stops waiting for your extractor and throws; work that does not look at the signal goes on in the background until it ends. |
802
+ | `maxTextBytes` | `maxTextBytes` of `createLargeFiles`: the most text kept from one file, in UTF-8 bytes. | Refuse the file as soon as your text passes it, with a message for the user. `ingest` refuses a larger text when you return it, but by then it is all in memory. |
803
+ | `maxPages` | `maxPdfPages` of `createLargeFiles`: the most pages read from one PDF. | In a PDF extractor, refuse a file with more pages before you read them. `ingest` does not check it for you. |
804
+
805
+ The built-in PDF, DOCX and PPTX extractors honour all three, so an extractor that wraps one, as the
806
+ OCR example below does, gets them by passing `input` on. The text extractor decodes a valid UTF-8
807
+ file in one step, and a file in another encoding in steps that stop when `signal` aborts; its text
808
+ is checked against `maxTextBytes` when it returns.
809
+
810
+ The eight formats are fixed: you can replace the extractor of a format, not add a format. A file of
811
+ another kind, such as HTML or XLSX, is detected as `text`, so it goes to the `text` extractor: check
812
+ the name or the MIME type there ([Other formats](#other-formats)).
813
+
814
+ What the library does with what you return:
815
+
816
+ - The text is made uniform, as for the built-in extractors ([Formats](#formats)). A text that is
817
+ empty is refused: `report.pdf did not contain any text.`
818
+ - `pages` becomes `meta.pages`, which the card, the system instruction and `toDocumentSummary` show.
819
+ - `encoding`, the older encoding your extractor read the file in, becomes `meta.encoding`. It is
820
+ kept when it is a name such as `iso-8859-2`, and dropped when it names UTF-8 or UTF-16 (`utf-8`,
821
+ `utf8`, `unicode`, `utf-16be`…), or is not such a name: a value that is not a string, is longer
822
+ than 40 characters, or holds a character other than letters, digits, `.`, `_`, `:` and `-` (a
823
+ space, say).
824
+ - `replacedCharacters`, a whole number above 0, becomes `meta.replacedCharacters`: the characters
825
+ your extractor stored as U+FFFD. Both reach the card, the frame of a file sent whole, and
826
+ `toDocumentSummary` ([Text encodings](#text-encodings)).
827
+ - A `text` file whose lines look like a log becomes `log`.
828
+
829
+ An error you throw is the answer to the upload. `createDocumentHandlers` answers 422 with its
830
+ message, unless the error has a `status` (or `statusCode`) from 400 to 599: then it answers that
831
+ status, with your message. A status of 413 is answered with the upload-limit message instead of
832
+ yours. An error with a Node system `code` and `syscall` (from `fs` or a socket) is answered 500,
833
+ `Upload failed (ENOENT).`, without its message. A value that is not an `Error`, such as a thrown
834
+ string, is answered 500 too: `Upload failed.` Write messages a user can read, and give a status
835
+ when the fault is on your side, such as an OCR service that is down.
836
+
837
+ ### Rules for a PDF extractor
838
+
839
+ The tools find pages through the text, so a PDF extractor of your own must write it the way the
840
+ built-in one does:
841
+
842
+ 1. **Start each page with a line `--- Page N ---`,** exactly that, on a line of its own, with N
843
+ counting from 1 in page order. Only lines that continue the count are taken for pages. Search and
844
+ read results take their page numbers from these lines, and the model passes them to
845
+ `view_pages`. Without them, the model cannot tell which page a line is on.
846
+ 2. **Return `pages`, the number of pages of the file.** `view_pages` refuses to cut a file in which
847
+ `@cantoo/pdf-lib` counts another number, since a page number could then point at the wrong page.
848
+ Without `pages`, that check is not made, and the card and the instruction give no page count.
849
+ 3. **Honour `input.scannedPages`.** The library sets it on every PDF it ingests when PDFs are kept
850
+ (`keepOriginals` lists `"pdf"` and the store has `putOriginal`) and `scannedPdfPages` is above 0.
851
+ It does not say that the file has no text: its value is `scannedPdfPages`, the most pages a PDF
852
+ without any text may have. Unset, refuse a PDF in which you found no text. The library does not check
853
+ this for you: page lines alone are text, so a scan your extractor lets through is stored even
854
+ when the model can never see it.
855
+
856
+ The simplest way to keep all of this, and the rebuilt tables and picture marks, is to wrap
857
+ `createPdfExtractor()` and change only what you need, as the OCR example below does.
858
+
859
+ ### OCR
860
+
861
+ The library does no OCR. To make scans searchable, wrap the built-in PDF extractor and fill in the
862
+ pages it found no text on with the text of your OCR service. Here `OCR_URL` is a service of your own
863
+ that takes a PDF and answers `{ "pages": ["text of page 1", "text of page 2", ...] }`; Document AI,
864
+ Textract or Tesseract can stand behind it.
865
+
866
+ ```ts
867
+ import { createLargeFiles, createPdfExtractor, FileDocumentStore, type Extractor } from "llm-large-files";
868
+
869
+ /** The text of each page of a PDF, in page order, from your OCR service. */
870
+ async function recognizePages(pdf: Uint8Array, signal: AbortSignal | undefined): Promise<string[]> {
871
+ const response = await fetch(process.env.OCR_URL!, {
872
+ method: "POST",
873
+ headers: { "Content-Type": "application/pdf" },
874
+ body: Buffer.from(pdf),
875
+ signal, // the ingest's time limit stops the request too
876
+ });
877
+ if (!response.ok) throw new Error(`The OCR service answered ${response.status}.`);
878
+ const { pages } = (await response.json()) as { pages: string[] };
879
+ return pages;
880
+ }
881
+
882
+ const builtIn = createPdfExtractor();
883
+ /** A page the built-in extractor found no text on: its line, the picture line if any, and the line that says it has no text. */
884
+ const PAGE_WITHOUT_TEXT =
885
+ /^(--- Page (\d+) ---\n(?:\[Picture on this page\. This text cannot show it\.\]\n)?)\[No text on this page\. It may be a scan, a photo, or a chart\.\]$/gm;
886
+
887
+ const pdfWithOcr: Extractor = async (bytes, input) => {
888
+ // Let a PDF without any text through for now: OCR may give it some.
889
+ const extracted = await builtIn(bytes, { ...input, scannedPages: Number.MAX_SAFE_INTEGER });
890
+ const blank = [...extracted.text.matchAll(PAGE_WITHOUT_TEXT)].length;
891
+ if (blank === 0) return extracted;
892
+
893
+ let recognized: string[];
894
+ try {
895
+ recognized = await recognizePages(bytes, input.signal);
896
+ } catch (error) {
897
+ // Stopped by the ingest's time limit or its caller: throw what stopped it.
898
+ input.signal?.throwIfAborted();
899
+ // With a status, the upload answers 503 and this message, not 422 and the service's own error.
900
+ throw Object.assign(new Error("Text recognition is not available. Try again later.", { cause: error }), { status: 503 });
901
+ }
902
+
903
+ let filled = 0;
904
+ const text = extracted.text.replace(PAGE_WITHOUT_TEXT, (page, header: string, number: string) => {
905
+ const words = recognized[Number(number) - 1]?.trim();
906
+ if (!words) return page;
907
+ filled++;
908
+ return `${header}${words}`;
909
+ });
910
+ // Nothing recognized in a PDF without any text: the built-in rules decide. It is refused, or
911
+ // accepted when its pages can be shown.
912
+ if (filled === 0 && blank === extracted.pages) return builtIn(bytes, input);
913
+ return { text, pages: extracted.pages };
914
+ };
915
+
916
+ export const files = createLargeFiles({
917
+ store: new FileDocumentStore("./data/large-files"),
918
+ keepOriginals: ["pdf"],
919
+ extractors: { pdf: pdfWithOcr },
920
+ });
921
+ ```
922
+
923
+ What this keeps: the page lines, so search results still give page numbers; `pages`; the rebuilt
924
+ tables and the picture marks of the pages that had text; and the picture line over a scanned page,
925
+ since the model can still look at it to check a stamp or a signature. Only PDFs with a page without
926
+ text go to the OCR service, and only those pages change. A scan of any length is accepted once OCR
927
+ found text in it.
928
+
929
+ OCR runs inside `files.ingest`, so the upload waits for it, and it counts toward `ingestTimeoutMs`
930
+ (2 minutes by default). For long scans, raise `ingestTimeoutMs` (0 sets no limit), run ingest in a
931
+ background job, and tell the user when the file is ready ([Web app](./web-app.md)).
932
+
933
+ ### Other formats
934
+
935
+ A file the library does not know arrives at the `text` extractor. This one converts HTML to text,
936
+ with the `html-to-text` package here (any converter works), and leaves every other file to the
937
+ built-in extractor:
938
+
939
+ ```ts
940
+ import { convert } from "html-to-text";
941
+ import { createLargeFiles, defaultExtractors, FileDocumentStore, type Extractor } from "llm-large-files";
942
+
943
+ const text: Extractor = async (bytes, input) => {
944
+ // The built-in extractor decodes UTF-8 and UTF-16, reads Hebrew, Arabic, Cyrillic, Japanese and
945
+ // Western files in their older encodings, and refuses binary files.
946
+ const decoded = await defaultExtractors.text(bytes, input);
947
+ const html = /\.html?$/i.test(input.name) || input.mimeType.startsWith("text/html");
948
+ // `...decoded` keeps `encoding` and `replacedCharacters`: the model is told how the file was read.
949
+ return html ? { ...decoded, text: convert(decoded.text, { wordwrap: false }) } : decoded;
950
+ };
951
+
952
+ export const files = createLargeFiles({
953
+ store: new FileDocumentStore("./data/large-files"),
954
+ extractors: { text },
955
+ });
956
+ ```
957
+
958
+ Its format stays `text`. To read XLSX, test for its name the same way, before the built-in
959
+ extractor, which refuses ZIP files, and write each sheet as lines of text.
960
+
961
+ ## Your own tool loop
962
+
963
+ `view_pages` returns a file, and a loop that dropped it would tell the model that pages are attached
964
+ when nothing is. So `files.tools()` declares it only when you say that your loop delivers files:
965
+ pass `viewPages: true` to `files.prepare()`, pass `prepared.viewable` as `viewPages` to
966
+ `files.tools()`, run calls with `executeWithFiles`, and send each file it returns with its tool
967
+ result, in your provider's form. `execute("view_pages", …)` answers with an error instead:
968
+ `The pages could not be shown: this application does not pass files from tools to the model. Answer from the text.`
969
+ Without limits, one call may use 3/8 of what is left of `maxRequestBytes` after 256 KB (3,651,696
970
+ bytes with the default of 10,000,000), and five pages.
971
+ [Your own adapter and loop](./own-adapter-and-loop.md) walks through it.