llm-large-files 0.5.0 → 0.8.0

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