llm-large-files 0.1.0 → 0.3.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 (91) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +32 -6
  3. package/dist/analyze.d.ts.map +1 -1
  4. package/dist/analyze.js +5 -1
  5. package/dist/analyze.js.map +1 -1
  6. package/dist/extract.d.ts +30 -7
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +94 -23
  9. package/dist/extract.js.map +1 -1
  10. package/dist/gemini/chat.d.ts +38 -2
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +83 -32
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts +34 -4
  15. package/dist/gemini/generate.d.ts.map +1 -1
  16. package/dist/gemini/generate.js +51 -8
  17. package/dist/gemini/generate.js.map +1 -1
  18. package/dist/gemini/index.d.ts +3 -3
  19. package/dist/gemini/index.d.ts.map +1 -1
  20. package/dist/gemini/index.js +2 -2
  21. package/dist/gemini/index.js.map +1 -1
  22. package/dist/index.d.ts +4 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/library.d.ts +37 -1
  27. package/dist/library.d.ts.map +1 -1
  28. package/dist/library.js +59 -7
  29. package/dist/library.js.map +1 -1
  30. package/dist/map-reduce.d.ts +7 -0
  31. package/dist/map-reduce.d.ts.map +1 -1
  32. package/dist/map-reduce.js +58 -16
  33. package/dist/map-reduce.js.map +1 -1
  34. package/dist/pdf-layout.d.ts +39 -0
  35. package/dist/pdf-layout.d.ts.map +1 -0
  36. package/dist/pdf-layout.js +820 -0
  37. package/dist/pdf-layout.js.map +1 -0
  38. package/dist/pdf-pages.d.ts +45 -0
  39. package/dist/pdf-pages.d.ts.map +1 -0
  40. package/dist/pdf-pages.js +336 -0
  41. package/dist/pdf-pages.js.map +1 -0
  42. package/dist/pdf-pictures.d.ts +20 -0
  43. package/dist/pdf-pictures.d.ts.map +1 -0
  44. package/dist/pdf-pictures.js +336 -0
  45. package/dist/pdf-pictures.js.map +1 -0
  46. package/dist/plan.d.ts +13 -3
  47. package/dist/plan.d.ts.map +1 -1
  48. package/dist/plan.js +27 -18
  49. package/dist/plan.js.map +1 -1
  50. package/dist/search.d.ts +17 -4
  51. package/dist/search.d.ts.map +1 -1
  52. package/dist/search.js +90 -24
  53. package/dist/search.js.map +1 -1
  54. package/dist/stores.d.ts +7 -1
  55. package/dist/stores.d.ts.map +1 -1
  56. package/dist/stores.js +37 -5
  57. package/dist/stores.js.map +1 -1
  58. package/dist/text.d.ts +18 -4
  59. package/dist/text.d.ts.map +1 -1
  60. package/dist/text.js +155 -15
  61. package/dist/text.js.map +1 -1
  62. package/dist/tools.d.ts +11 -0
  63. package/dist/tools.d.ts.map +1 -1
  64. package/dist/tools.js +156 -16
  65. package/dist/tools.js.map +1 -1
  66. package/dist/types.d.ts +63 -3
  67. package/dist/types.d.ts.map +1 -1
  68. package/docs/api.md +56 -11
  69. package/docs/configuration.md +298 -6
  70. package/docs/getting-started.md +41 -7
  71. package/docs/how-it-works.md +77 -11
  72. package/docs/security.md +54 -6
  73. package/package.json +96 -91
  74. package/src/analyze.ts +3 -1
  75. package/src/extract.ts +105 -24
  76. package/src/gemini/chat.ts +116 -34
  77. package/src/gemini/generate.ts +66 -10
  78. package/src/gemini/index.ts +3 -3
  79. package/src/index.ts +4 -3
  80. package/src/library.ts +308 -226
  81. package/src/map-reduce.ts +69 -16
  82. package/src/node/handlers.ts +122 -122
  83. package/src/pdf-layout.ts +807 -0
  84. package/src/pdf-pages.ts +315 -0
  85. package/src/pdf-pictures.ts +324 -0
  86. package/src/plan.ts +120 -98
  87. package/src/search.ts +85 -25
  88. package/src/stores.ts +165 -132
  89. package/src/text.ts +131 -14
  90. package/src/tools.ts +408 -264
  91. package/src/types.ts +228 -168
package/docs/api.md CHANGED
@@ -20,6 +20,8 @@ Three entry points:
20
20
  | `maxUploadBytes` | `number` | 100 MB |
21
21
  | `extractors` | `Partial<Record<DocumentFormat, Extractor>>` | built-ins |
22
22
  | `cacheSize` | `number` | 6 parsed documents in memory |
23
+ | `keepOriginals` | `DocumentFormat[]` | `[]`: only text is kept. `["pdf"]` keeps uploaded PDFs, which `view_pages` needs ([details](configuration.md#keeping-the-uploaded-file)) |
24
+ | `scannedPdfPages` | `number` | 30: the longest PDF without any text that is accepted when its original is kept. 0 refuses them all |
23
25
 
24
26
  ### `LargeFiles`
25
27
 
@@ -27,10 +29,11 @@ Three entry points:
27
29
  |---|---|
28
30
  | `ingest({ name, mimeType?, bytes, owner? })` | Extracts, normalizes, profiles, and stores a file. Returns `DocumentMeta`. Throws an `Error` with a user-readable message for empty, oversized, binary, or text-less files. |
29
31
  | `getMeta(id, { owner }?)` | `DocumentMeta`, or `undefined` if unknown, expired, or owned by someone else. |
32
+ | `getOriginal(id, { owner }?)` | The uploaded file as a `Uint8Array`, when it was kept. `undefined` otherwise, and for another owner. |
30
33
  | `delete(id, { owner }?)` | `true` if deleted. |
31
34
  | `sweep()` | Removes expired documents; returns the count. |
32
- | `prepare(ids, base, { owner }?)` | Plans one request. `base` is `{ tokens, bytes }` for everything else in the request. Returns `PreparedContext`. |
33
- | `tools(documents, { generate?, onProgress?, signal? })` | A `ToolSet` scoped to these documents. `generate` enables `analyze_whole_document`. |
35
+ | `prepare(ids, base, { owner?, viewPages? }?)` | Plans one request. `base` is `{ tokens, bytes }` for everything else in the request. Returns `PreparedContext`. `viewPages: true` says that your loop can pass files to the model. |
36
+ | `tools(documents, { generate?, onProgress?, signal?, viewPages? })` | A `ToolSet` scoped to these documents. `generate` enables `analyze_whole_document`. `viewPages` (`true`, or a list of documents such as `prepared.viewable`) enables `view_pages`. |
34
37
  | `budget`, `maxUploadBytes` | The effective settings. |
35
38
 
36
39
  ### `PreparedContext`
@@ -39,8 +42,9 @@ Three entry points:
39
42
  {
40
43
  plan: { inline: DocumentMeta[]; searchable: DocumentMeta[]; inlineTokens: number; inlineBytes: number };
41
44
  blocks: Map<string, string>; // per document ID: full text (inline) or a summary card (searchable)
42
- instruction: string; // add to the system prompt; empty when nothing is searchable
45
+ instruction: string; // add to the system prompt; empty when there is nothing to search or to look at
43
46
  missing: string[]; // IDs not found (never uploaded, expired, or another owner's)
47
+ viewable: DocumentMeta[]; // PDFs whose pages view_pages can show; empty without viewPages: true
44
48
  }
45
49
  ```
46
50
 
@@ -51,22 +55,32 @@ Three entry points:
51
55
  declarations: ToolDeclaration[]; // { name, description, parameters: JSON Schema }
52
56
  has(name): boolean;
53
57
  execute(name, args): Promise<ToolResult>; // errors come back as { error } for the model to read
58
+ executeWithFiles(name, args, { maxFileBytes?, maxPages? }?): Promise<{ result: ToolResult; files: ToolFile[] }>;
54
59
  describe(name, args): string; // "Search app.log (exact) for “timeout”"
55
60
  }
56
61
  ```
57
62
 
63
+ `executeWithFiles` runs any tool. Its `files` (`{ name, mimeType, bytes }`) are empty for all but
64
+ `view_pages`. `execute("view_pages", …)` returns an error, because it has no place for the file.
65
+
58
66
  | Tool | Arguments | Returns |
59
67
  |---|---|---|
60
68
  | `search_document` | `document_id`, `query`, `mode`: `keywords` (default) \| `exact` \| `regex`, `max_results`, `context_lines`, `case_sensitive` | `keywords`: ranked passages with numbered lines. `exact`/`regex`: matching lines and `total_matching_lines`. |
61
69
  | `read_document` | `document_id`, `start_line`, `end_line?` | Up to 600 numbered lines, and `next_start_line` if there's more |
62
70
  | `get_document_overview` | `document_id` | Format, size, outline, log profile, first and last lines |
63
71
  | `analyze_whole_document` | `document_id`, `task` | `answer` from a map-reduce read, plus part counts |
72
+ | `view_pages` | `document_id`, `from_page`, `to_page?` | Up to 5 pages of a PDF as one PDF file, with `pages` ("12-14"), `total_pages`, `file` (its name), and `next_page` when fewer pages were given than asked. Declared only with `viewPages`, for PDFs whose original is kept. |
73
+
74
+ For a PDF that `view_pages` can show, the results of `search_document` and `read_document` also
75
+ carry page numbers: `page` on each matching line, `pages` on a passage and on a range that was read.
64
76
 
65
77
  ### Stores
66
78
 
67
79
  - `new MemoryDocumentStore({ now? })`: in-process, for tests and single-instance demos.
68
- - `new FileDocumentStore(directory, { now? })`: `<id>.txt` and `<id>.json` per document.
69
- - Implement `DocumentStore` (`put`, `get`, `getMeta`, `delete`, `sweep?`) for anything else.
80
+ - `new FileDocumentStore(directory, { now? })`: `<id>.txt` and `<id>.json` per document, and
81
+ `<id>.bin` for a kept original.
82
+ - Implement `DocumentStore` (`put`, `get`, `getMeta`, `delete`, `sweep?`, and `putOriginal?` with
83
+ `getOriginal?` to keep originals) for anything else.
70
84
 
71
85
  ### Helpers
72
86
 
@@ -74,7 +88,12 @@ Three entry points:
74
88
  - `toolResultSummary(label, result)`: `" — 12 matching lines"`, for step lists.
75
89
  - `isDocumentId(value)`, `DOCUMENT_ID_PATTERN`.
76
90
  - `estimateTokens(text)`, `utf8Bytes(text)`, `jsonBytes(text)`.
77
- - `detectFormat(name, mimeType)`, `defaultExtractors`, `TOOL_NAMES`, `DEFAULT_BUDGET`.
91
+ - `detectFormat(name, mimeType)`, `defaultExtractors`, `TOOL_NAMES`, `DEFAULT_BUDGET`,
92
+ `MAX_VIEW_PAGES` (5).
93
+ - `createPdfExtractor({ tables?: boolean, pictures?: boolean })`: the built-in PDF extractor with
94
+ an option changed. `tables: false` gives the text in pdf.js order, without rebuilt tables
95
+ (see [PDF tables](configuration.md#pdf-tables)). `pictures: false` leaves out the line that marks
96
+ a page with a picture (see [Pictures in PDFs](configuration.md#pictures-in-pdfs)).
78
97
 
79
98
  ### Key types
80
99
 
@@ -85,14 +104,21 @@ type DocumentMeta = {
85
104
  id: string; owner?: string; name: string; mimeType: string; format: DocumentFormat;
86
105
  bytes: number; textBytes: number; characters: number; lines: number; estimatedTokens: number;
87
106
  wrappedLines: number; pages?: number;
107
+ originalKept?: boolean; // the uploaded file is in the store next to the text
88
108
  outline: { line: number; level: number; title: string }[];
89
109
  logProfile?: { levels: Record<string, number>; firstTimestamp?: string; lastTimestamp?: string;
90
110
  topIssues: { template: string; level: string; count: number; firstLine: number }[] };
91
111
  createdAt: string; expiresAt: string;
92
112
  };
93
113
 
94
- type GenerateText = (request: { system: string; prompt: string; maxOutputTokens: number; signal?: AbortSignal }) => Promise<string>;
95
- type Extractor = (bytes: Uint8Array, input: { name: string; mimeType: string; format: DocumentFormat }) => Promise<{ text: string; pages?: number }>;
114
+ type GenerateText = (request: {
115
+ system: string; prompt: string; maxOutputTokens: number; signal?: AbortSignal;
116
+ onTruncated?: () => void; // call it when the model stopped at maxOutputTokens
117
+ }) => Promise<string>;
118
+ type Extractor = (bytes: Uint8Array, input: { name: string; mimeType: string; format: DocumentFormat; scannedPages?: number }) => Promise<{ text: string; pages?: number }>;
119
+ // scannedPages: set when a PDF without any text is welcome, with the most pages it may have.
120
+
121
+ type ToolFile = { name: string; mimeType: string; bytes: Uint8Array };
96
122
  ```
97
123
 
98
124
  ## `llm-large-files/gemini`
@@ -107,13 +133,26 @@ type Extractor = (bytes: Uint8Array, input: { name: string; mimeType: string; fo
107
133
  | `system` | System instruction; the tool guide is appended when needed. |
108
134
  | `generationConfig` | Sent with every chat request. |
109
135
  | `owner` | Only documents with this owner (or no owner) are used. |
110
- | `maxToolTurns` | Default 12. A final tool-free turn always follows if needed. |
136
+ | `documentPlacement` | `"first"` (default): document text and cards go at the start of the first user turn and stay there, so follow-up questions reuse Gemini's prompt cache. `"last"`: appended to the latest user turn, as in 0.1.0. |
137
+ | `maxToolTurns` | Default 12. The most requests for one question, counting the answer. If the model is still calling tools on the last one, it is sent with no tools so the model must answer. |
111
138
  | `wholeDocumentAnalysis` | Default `true`. Set `false` to withhold the costly whole-file tool. |
139
+ | `viewPages` | Default `true`. Offers `view_pages` for PDFs whose original is kept. It changes nothing for a library that keeps no originals. |
140
+ | `toolFilePlacement` | `"inside"` (default): the pages go in the function response itself, which Gemini 3 models read. `"beside"`: in a user turn of their own after the function responses, for Gemini 2.5, which does not see a file inside a function response. See [Where the pages go](configuration.md#where-the-pages-go-toolfileplacement). |
112
141
  | `analysisConfig` | `(maxOutputTokens) => generationConfig` for whole-file part reads. |
113
142
  | `onText`, `onActivity`, `onStep` | Streaming answer text, transient status, completed steps. |
114
143
  | `fetch`, `signal` | Custom fetch (proxies, tests) and cancellation. |
115
144
 
116
- Returns `{ text, steps, plan, turns, finishReason?, usage? }`.
145
+ Returns `{ text, answered, blockReason?, steps, plan, turns, finishReason?, usage? }`.
146
+
147
+ `answered` is `false` when the model's last turn had no text: the prompt was blocked
148
+ (`blockReason` says why), the reply was cut off before any text, or the model produced a malformed
149
+ tool call and the tool-free retry came back empty too. `text` is then empty or holds only a remark
150
+ the model made before a tool call, so show your own message:
151
+
152
+ ```ts
153
+ const result = await askGemini({ ... });
154
+ if (!result.answered) show(result.blockReason ? "The request was blocked." : "No answer this time. Try again.");
155
+ ```
117
156
 
118
157
  It throws `DocumentsNotFoundError` (`.ids`) before calling the model, `GeminiRequestError` (`.status`)
119
158
  for HTTP errors, and `Error` when the last message isn't the user's.
@@ -129,7 +168,13 @@ for HTTP errors, and `Error` when the last message isn't the user's.
129
168
 
130
169
  - `createGeminiGenerateText({ url, headers, fetchImpl?, generationConfig?, timeoutMs? })`: a `GenerateText` for your own loop.
131
170
  - `toGeminiTools(declarations)`: `{ functionDeclarations }`.
132
- - `geminiFunctionResponses([{ call, result }])`: the `user` turn answering function calls.
171
+ - `geminiFunctionResponses([{ call, result, files? }])`: the `user` turn answering function
172
+ calls. Files from `executeWithFiles` go inside their function response, as base64.
173
+ - `geminiFunctionResponseTurns([{ call, result, files? }], { files?: "inside" | "beside" })`: the
174
+ turns to add to `contents`. That is the one turn above, or with `"beside"` the function
175
+ responses followed by a `user` turn that holds the files.
176
+ - `FINAL_ANSWER_REQUEST`, `FINAL_ANSWER_AFTER_PAGES`: the messages `askGemini` adds when the model
177
+ must stop using tools. The second is used when `view_pages` was the only tool.
133
178
  - `parseSseJson(stream)`: async iterator over a Generate Content SSE stream.
134
179
 
135
180
  ## `llm-large-files/node`
@@ -13,7 +13,7 @@ planner uses them to decide what goes into a request whole.
13
13
  | `reservedTokens` | 64,000 | Kept free for the answer, tool results, and growing history. |
14
14
  | `mapChunkTokens` | 100,000 | Part size when a whole file is read in parts. Smaller parts give more detailed notes but more model calls. |
15
15
  | `maxMapChunks` | 30 | Refuse whole-file reads needing more model calls than this. 30 parts × 100K tokens = 3M tokens of input. |
16
- | `toolResultCharacters` | 24,000 | Cap on one tool result. |
16
+ | `toolResultCharacters` | 24,000 | Cap on one tool result, in characters. For a log that can be 16,000 tokens, and every result is sent again on each later turn. |
17
17
 
18
18
  ```ts
19
19
  createLargeFiles({
@@ -34,9 +34,27 @@ A document is sent whole if it fits both. Otherwise it becomes searchable.
34
34
 
35
35
  ### Token estimates
36
36
 
37
- `estimateTokens` counts about 4 characters per token for ASCII and 1.5 for other scripts
38
- (Hebrew, Arabic, CJK, …). That's deliberately conservative: overestimating only makes a file
39
- searchable a little sooner. On English text it matched Gemini's own count within 0.01%.
37
+ `estimateTokens` prices each kind of character, because characters per token depends on the kind
38
+ of text. As counted by Gemini:
39
+
40
+ | Text | Characters per token |
41
+ |---|---|
42
+ | English prose | 4.3 to 5.0 |
43
+ | Source code | 3.5 to 4.1 |
44
+ | Hebrew, Arabic, Russian prose | 2.1 to 3.3 |
45
+ | Chinese, Japanese, Korean prose | 1.4 to 1.7 |
46
+ | Logs (timestamps, IDs, IP addresses) | 1.4 to 2.8 |
47
+ | CSV of numbers, hex dumps, base64 | 1.0 to 1.4 |
48
+
49
+ Digits cost about one token each, which is why a log is three times denser than a novel of the
50
+ same size. The estimate was fitted to Gemini's `countTokens` on 60 texts (Gemini 2.5, 3.5, and 3.8
51
+ count identically) and lands between 0.98 and 1.7 times the real count. It leans high on purpose:
52
+ overestimating only makes a file searchable a little sooner. The one kind of text it still counts
53
+ low, at about 70%, is a long run of random letters in one case with no digits.
54
+
55
+ Tokenizers differ between providers. These weights are fitted to Gemini, which counts digits one
56
+ by one. A tokenizer that groups digits will count fewer tokens than this estimate for logs and
57
+ data, which is the safe direction.
40
58
 
41
59
  ## Stores
42
60
 
@@ -51,14 +69,36 @@ interface DocumentStore {
51
69
  put(document: { meta: DocumentMeta; text: string }): Promise<void>;
52
70
  get(id: string): Promise<{ meta: DocumentMeta; text: string } | undefined>; // undefined if expired
53
71
  getMeta(id: string): Promise<DocumentMeta | undefined>;
54
- delete(id: string): Promise<boolean>;
72
+ delete(id: string): Promise<boolean>; // the original file too
55
73
  sweep?(now?: Date): Promise<number>;
74
+ putOriginal?(id: string, bytes: Uint8Array): Promise<void>; // optional: see below
75
+ getOriginal?(id: string): Promise<Uint8Array | undefined>; // undefined if not kept, or expired
56
76
  }
57
77
  ```
58
78
 
59
79
  Keep `getMeta` cheap (store the metadata separately from the text). Parsed documents are cached
60
80
  in memory (`cacheSize`, default 6), so repeated tool calls don't reload the text.
61
81
 
82
+ ### Keeping the uploaded file
83
+
84
+ By default a store holds only the text of a document. `keepOriginals` also keeps the uploaded file,
85
+ which is what [showing pages of a PDF](#pictures-in-pdfs) needs:
86
+
87
+ ```ts
88
+ createLargeFiles({ store: new FileDocumentStore(dir), keepOriginals: ["pdf"] });
89
+ ```
90
+
91
+ - It is off by default because it costs disk: a kept file is as large as the upload (up to
92
+ `maxUploadBytes`, 100 MB) and stays until the document expires or is deleted.
93
+ - `FileDocumentStore` writes it as `<id>.bin` next to `<id>.txt` and `<id>.json`.
94
+ `MemoryDocumentStore` keeps a copy in memory.
95
+ - A store of your own keeps originals when it has `putOriginal` and `getOriginal`. `putOriginal` is
96
+ called before `put` for the same ID, and `delete` and `sweep` must remove the file. A store
97
+ without the two methods works as before: nothing is kept, and `view_pages` is not offered.
98
+ - `DocumentMeta.originalKept` says whether a document's file is kept. `files.getOriginal(id, { owner })`
99
+ returns it.
100
+ - Documents ingested before you turned it on have no original. Upload them again to get one.
101
+
62
102
  ## Formats
63
103
 
64
104
  | Format | Detected by | Notes |
@@ -67,12 +107,264 @@ in memory (`cacheSize`, default 6), so repeated tool calls don't reload the text
67
107
  | `markdown` | `.md`, `.markdown`, `text/markdown` | Headings form the outline |
68
108
  | `json` | `.json`, `.jsonl`, `.ndjson` | Minified JSON is wrapped into addressable lines |
69
109
  | `csv` | `.csv`, `.tsv` | |
70
- | `pdf` | `.pdf` | Needs `unpdf`. Pages are marked `--- Page N ---`. Scanned PDFs (no text layer) are rejected. |
110
+ | `pdf` | `.pdf` | Needs `unpdf`. Pages are marked `--- Page N ---`, tables are rebuilt (below), and a page without text says so. With `@cantoo/pdf-lib`, a page that shows a picture says so too, and the model can be shown the page itself ([Pictures in PDFs](#pictures-in-pdfs)). A scanned PDF (no text layer at all) is rejected, unless its original is kept and it has at most 30 pages. |
71
111
  | `docx`, `pptx` | extension or MIME type | Needs `jszip`. Slides are marked `## Slide N`. |
72
112
  | `text` | anything else that decodes as text | UTF-8 or UTF-16 (with or without BOM); binary is rejected |
73
113
 
74
114
  Lines longer than 2,000 characters are split, so every line can be read by number.
75
115
 
116
+ ### PDF tables
117
+
118
+ A PDF stores no tables, only text at positions. Read in file order, a row with an empty cell looks
119
+ like a row without that column: `EMEA 80 95 101` under the headings `Q1 Q2 Q3 Q4`, and a model
120
+ reads 95 as Q2. The PDF extractor finds tables by the position of their text and writes each row
121
+ with its cells marked, so the same row becomes:
122
+
123
+ ```
124
+ | Region | Q1 | Q2 | Q3 | Q4 |
125
+ | EMEA | 80 | | 95 | 101 |
126
+ ```
127
+
128
+ In a live test (`gemini-3.5-flash-lite`, 110 questions about single cells of seven PDFs made by
129
+ Word and Chrome, half of them about empty cells), 44 answers were right from the text in file
130
+ order and 110 from the rebuilt rows.
131
+
132
+ What it handles: empty cells, tables inside one column of a two-column page, right-to-left tables
133
+ (the first column is the rightmost), tables printed sideways, rotated pages, footnote marks,
134
+ headings that span columns, and cells whose text wraps onto several lines when the rows are
135
+ visibly spaced apart. Text that is not a table (paragraphs, lists, columns of prose, justified
136
+ text) is left as pdf.js gives it.
137
+
138
+ It is cautious: where the evidence for a table is weak, the text stays as it was. So:
139
+
140
+ - Two-column tables (key and value, a glossary) are left as lines of text. They read correctly
141
+ that way.
142
+ - When a cell wraps and the rows have no extra space between them, each line of the cell is a row
143
+ of its own, with the other cells empty.
144
+ - Columns that are closer together than a word space on every line of the table stay together in
145
+ one cell, on every row alike.
146
+ - A table whose text is stored column by column in the file is not rebuilt.
147
+ - Pictures and charts are not in the text. A page with no text at all is written as
148
+ `[No text on this page. It may be a scan, a photo, or a chart.]`, so the model can say that it
149
+ cannot see it. To let the model look at such pages, see [Pictures in PDFs](#pictures-in-pdfs).
150
+
151
+ The cell marks cost tokens: about one per cell. A bank statement came to 27% more tokens than
152
+ its text in file order, a report with one table in it to 9% more. Reading 600 pages with 24,600
153
+ table rows took 1.6 seconds instead of 1.3.
154
+
155
+ The rules were tuned on PDFs made by Chrome and by Word. To get the text of version 0.1.0 instead:
156
+
157
+ ```ts
158
+ import { createLargeFiles, createPdfExtractor } from "llm-large-files";
159
+
160
+ createLargeFiles({ store, extractors: { pdf: createPdfExtractor({ tables: false }) } });
161
+ ```
162
+
163
+ Small PDFs are still better sent to Gemini as the file itself, when your payload limit allows:
164
+ it then sees every page, including pictures. For a PDF that is too large for that, the next section
165
+ gives the model the pages it asks for.
166
+
167
+ ## Pictures in PDFs
168
+
169
+ The text of a PDF does not hold its photos, charts and diagrams. Asked about a bar chart from the
170
+ text alone, a model can only say that it cannot see it, or guess. Two things, both optional and
171
+ both for PDFs only, close that gap:
172
+
173
+ 1. **A line in the text that says where the pictures are.**
174
+ 2. **A tool, `view_pages`, that hands the model the real pages** as a small PDF, when it asks.
175
+
176
+ ```bash
177
+ npm install @cantoo/pdf-lib # optional dependency, needed for both
178
+ ```
179
+
180
+ ```ts
181
+ const files = createLargeFiles({
182
+ store: new FileDocumentStore("./data/large-files"),
183
+ keepOriginals: ["pdf"], // needed for view_pages: it cuts pages out of the uploaded file
184
+ });
185
+ // askGemini then offers view_pages by itself. Nothing else changes in your code.
186
+ ```
187
+
188
+ ### The line that marks a page
189
+
190
+ At ingest, a page that shows a picture or a drawing gets one line under its header:
191
+
192
+ ```
193
+ --- Page 12 ---
194
+ [Picture on this page. This text cannot show it.]
195
+ Figure 3: sales by region.
196
+ ```
197
+
198
+ The words hold whether or not the model can look at the page later. A search for
199
+ `[Picture on this page` lists every such page.
200
+
201
+ What counts:
202
+
203
+ - **A picture:** the images on the page cover 3% of it or more, measured by the size they are
204
+ shown at, not by their pixels. A logo covers about 1%. An image that is on 30% of the pages (and
205
+ on three at least) is taken for a logo, a letterhead or a watermark, and does not count,
206
+ whatever its size.
207
+ - **A drawing:** shapes filled in three or more colours, outside the tables. Greys, rules, dots
208
+ and page backgrounds do not count, and neither does the shading of a table's cells.
209
+ - A page whose drawing instructions are larger than 2 MB: that is a map or a technical drawing.
210
+
211
+ What it gets wrong:
212
+
213
+ - Missed: a chart in one or two colours, and a chart or diagram drawn only with lines.
214
+ - Marked by mistake: a table with cells shaded in three colours, when the table itself was not
215
+ recognised (a table of two columns, for example).
216
+
217
+ The mark is a hint. `view_pages` works on any page, marked or not, and in a live test the model
218
+ looked at a one-colour chart that had only a caption (below).
219
+
220
+ The pages are found from the structure of the file, without decoding any image, so it is cheap:
221
+ a PDF of 200 photos (85 MB) took 0.3 s to ingest without marks and 0.8 s with them. No page is
222
+ marked, and the text is exactly that of version 0.2.0, when:
223
+
224
+ - `@cantoo/pdf-lib` is not installed;
225
+ - you turn it off: `createPdfExtractor({ pictures: false })`;
226
+ - the file declares more than 150,000 objects (reading it would take over two seconds), reading
227
+ took more than five seconds, or the file does not have the pages the text was read from.
228
+
229
+ One cost to know: a PDF whose streams do not state their length up front (Ghostscript writes them
230
+ so) is scanned byte by byte, about 30 ms per MB. A file of 100 MB written that way took 3 s to
231
+ ingest instead of 0.1 s.
232
+
233
+ ### `view_pages`
234
+
235
+ `view_pages(document_id, from_page, to_page)` cuts those pages out of the kept original and
236
+ returns them as one PDF. `askGemini` puts it inside the function response, and Gemini reads it
237
+ like any PDF: text, pictures and layout.
238
+
239
+ It is offered for every PDF whose original is kept, also for one whose text is already in the
240
+ prompt: a slide deck of photos has little text, so its text fits, and without the tool the model
241
+ would see none of its slides. Such a PDF gets `view_pages` and no search tools.
242
+
243
+ For a PDF that the model can look at, search and read results also say which page a line is on
244
+ (`"page": 12`), since a page number is what `view_pages` takes.
245
+
246
+ Limits:
247
+
248
+ | Limit | Value | When it is reached |
249
+ |---|---|---|
250
+ | Pages per call | 5 | The result says where to continue (`next_page`). |
251
+ | Bytes | 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 page that does not fit by itself gives an error, and the model answers from what it has. |
252
+ | Pages per question | `reservedTokens / 2 / 530`: 60 with the default budget | The tool says that no more pages can be looked at. |
253
+
254
+ Pages stay in the request until the question is answered, so every look makes the later requests
255
+ of that question larger. They are not sent again with the next question.
256
+
257
+ A page costs Gemini about 530 tokens, whatever is on it: 532 for each of 1, 2, 3 and 5 A4 pages,
258
+ and 527 for a 16:9 slide (`gemini-3.5-flash-lite`).
259
+
260
+ A cut holds the pages asked for and little else. Copying pages the simple way does not: a contents
261
+ page links to every section, and those pages came along, so the cut was 89% of the file. Here every
262
+ other page is emptied before copying, and a page that shares its resources with the whole file
263
+ (FPDF, TCPDF and jsPDF write PDFs that way) gets a list of its own.
264
+
265
+ | File | Pages cut | Size of the cut |
266
+ |---|---|---|
267
+ | Chrome, 72 photos, 100 MB | 5 | 7.0 MB (7%) |
268
+ | PowerPoint deck, 40 photos, 9.9 MB | 5 | 1.2 MB (13%) |
269
+ | Word report with a contents page, 7.5 MB | the contents page | 55 KB (0.7%) |
270
+ | All images in one shared list, 12 MB | 2 | 0.6 MB (5%) |
271
+
272
+ What a cut costs the server: the whole file is read into memory on every call.
273
+
274
+ | File | Time | Memory at the peak |
275
+ |---|---|---|
276
+ | 100 MB of photos, 900 objects | 0.06 s | about 300 MB |
277
+ | 100 MB written the way Ghostscript writes | 3 s | about 300 MB |
278
+ | 54 MB, 330,000 objects (a tagged table of 591 pages) | 4 to 5 s | about 700 MB |
279
+
280
+ A file that declares more than a million objects, or more than the free memory can hold, is not
281
+ cut: the tool tells the model that the pages cannot be shown.
282
+
283
+ Also handled: PDFs encrypted only to restrict printing or copying (they open without a password),
284
+ hidden layers (they stay hidden), rotated pages, and links. Not shown: a PDF that needs a password
285
+ to open, a damaged file, and a file in which this reader counts other pages than the text
286
+ extractor did. In each case the model gets a message and answers from the text.
287
+
288
+ ### Scanned PDFs
289
+
290
+ A PDF with no text at all has nothing to search, and is refused: `This PDF has no text layer`. When
291
+ its original is kept, the model can read it by looking at its pages, so a scan of **up to 30
292
+ pages** is accepted. Every page of its text says that it has no text, and the model gets
293
+ `view_pages`. A longer scan is still refused: it could only be read five pages at a time, and it
294
+ could not be searched.
295
+
296
+ ```ts
297
+ createLargeFiles({ store, keepOriginals: ["pdf"], scannedPdfPages: 30 }); // 30 is the default; 0 refuses all scans
298
+ ```
299
+
300
+ A PDF with text on any page was always accepted and still is, however many of its pages are scans.
301
+
302
+ ### Live results
303
+
304
+ `gemini-3.5-flash-lite` on the Gemini API, November 2026, through `ingest` and `askGemini`:
305
+
306
+ | Check | Result |
307
+ |---|---|
308
+ | Which bar of a chart is tallest and shortest, and their colours; a number on a sign in a photo. Text sent whole. | Looked at 2 pages unasked. All five facts right. From the text alone, the model said it could not see the chart. |
309
+ | The same, with the PDF searched instead | One look, all five right. |
310
+ | Ten questions that the text answers, about a PDF with a photo on each of its 60 pages | 0 of 10 looked at a page, with the text sent whole and with the PDF searched. 10 of 10 right both times. |
311
+ | A chart in one colour: a caption, but no mark | The model looked at the page and read the chart correctly. |
312
+ | Five pages in one look (five numbers on five signs) | All five right. 2,660 tokens for the pages. |
313
+ | A slide deck of 41 slides: a number on slide 8, a bar on slide 1 | Two looks, both right. |
314
+ | A PDF encrypted to restrict printing | One look, all right. |
315
+ | A scan of three pages (pictures of text) | One look at the three pages. Four of four facts right. |
316
+ | The request without tools that ends a question, after a look | Accepted, answered correctly, with the pages still in it. |
317
+
318
+ **Vertex AI**, with the same model (locations `global` and `eu`, November 2026): one look, two
319
+ looks in one model turn, one look that decides the next, the request without tools that ends a
320
+ question, and a PDF that is searched. All were accepted and answered correctly, with `vertexAi()`
321
+ and through an application's own URLs, streaming and not. Real files went through too: a number
322
+ on a photo in a 7.5 MB report written by Word, and five numbers from one look at five pages of a
323
+ 25 MB file (a 2.2 MB PDF in the request). A page costs 532 tokens there as well.
324
+
325
+ ### Where the pages go: `toolFilePlacement`
326
+
327
+ | `toolFilePlacement` | What is sent | Gemini 3.5 Flash-Lite, on the Gemini API and on Vertex AI | Gemini 2.5 Flash-Lite, on Vertex AI |
328
+ |---|---|---|---|
329
+ | `"inside"` (default) | The PDF in the `parts` of its function response, which names it as `{ "$ref": "pages-12-14.pdf" }` | Works | Accepted and counted, but the model does not see the pages |
330
+ | `"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 |
331
+
332
+ ```ts
333
+ await askGemini({ ..., toolFilePlacement: "beside" }); // for Gemini 2.5
334
+ ```
335
+
336
+ Keep the default for Gemini 3 models. Use `"beside"` for Gemini 2.5: it takes a file inside a
337
+ function response without an error, counts its tokens, and then answers that it cannot see the
338
+ page. Gemini 2.5 on the Gemini API was not checked (that model is closed to new users there), and
339
+ neither was Gemini 4.
340
+
341
+ With `"beside"` the files have a turn of their own because Vertex AI refuses a turn in which
342
+ anything follows a function response (HTTP 400, "Requests ending with a model turn are not
343
+ supported", seen with Gemini 3.5).
344
+
345
+ ### Your own loop
346
+
347
+ The pages are a file, and a loop that drops the file would tell the model that pages are attached
348
+ with nothing attached. So `view_pages` is declared only when you say that your loop delivers files:
349
+
350
+ ```ts
351
+ const prepared = await files.prepare(documentIds, base, { owner, viewPages: true });
352
+ const tools = files.tools(prepared.plan.searchable, { viewPages: prepared.viewable });
353
+
354
+ const { result, files: attached } = await tools.executeWithFiles(call.name, call.args, {
355
+ maxFileBytes: Math.floor(roomLeftInYourRequest * 3 / 4), // base64 turns three bytes into four
356
+ maxPages: pagesYouStillAllowForThisQuestion,
357
+ });
358
+ // attached: [{ name: "pages-12-14.pdf", mimeType: "application/pdf", bytes }]
359
+ // Send `result` as the tool result and each file as a PDF with it, in your provider's form.
360
+ // For Gemini, once every call of the model's turn is answered:
361
+ contents.push(...geminiFunctionResponseTurns(answers)); // answers: [{ call, result, files: attached }]
362
+ ```
363
+
364
+ `tools.execute("view_pages", ...)` returns only JSON, so it answers with an error instead of
365
+ pretending. `prepared.viewable` also lists PDFs that are not searched, because their text is in
366
+ the prompt: pass it as it is.
367
+
76
368
  ### Custom extractors
77
369
 
78
370
  Replace or add one per format, for example OCR for scanned PDFs, or HTML to text:
@@ -7,7 +7,8 @@ Express and Gemini, with notes for other setups.
7
7
 
8
8
  ```bash
9
9
  npm install llm-large-files
10
- npm install jszip unpdf # optional: DOCX/PPTX and PDF support
10
+ npm install jszip unpdf # optional: DOCX/PPTX and PDF support
11
+ npm install @cantoo/pdf-lib # optional: let the model look at pages of a PDF (pictures, charts)
11
12
  ```
12
13
 
13
14
  ## 2. Create the library once
@@ -22,6 +23,8 @@ export const files = createLargeFiles({
22
23
  budget: { contextTokens: 1_000_000, maxRequestBytes: 10_000_000 },
23
24
  ttlMs: 72 * 60 * 60 * 1000, // keep uploads for 3 days
24
25
  maxUploadBytes: 100 * 1024 * 1024,
26
+ // Optional: keep uploaded PDFs, so the model can look at their pages (see "Pictures" below).
27
+ // keepOriginals: ["pdf"],
25
28
  });
26
29
 
27
30
  // Reclaim disk space from expired uploads (expired files are already ignored on read).
@@ -58,7 +61,7 @@ The response is a `DocumentSummary`:
58
61
  ```
59
62
 
60
63
  Errors are JSON `{ "error": "…" }`: 400 when there's no file name, 413 when the file is too large,
61
- and 422 for an unreadable file (binary, empty, or a scanned PDF).
64
+ and 422 for an unreadable file (binary, empty, or a scanned PDF that cannot be shown page by page).
62
65
 
63
66
  **Other servers.** The handlers take Node's `IncomingMessage` / `ServerResponse`, so they work with
64
67
  `node:http`, Express, Koa (`ctx.req`, `ctx.res`), Fastify (`request.raw`, `reply.raw`), and Next.js
@@ -87,7 +90,8 @@ async function uploadLargeFile(file: File) {
87
90
  **Which files should go to the server?** Anything your current inline path can't handle. A
88
91
  practical rule is text over about 512 KB and PDFs over about 7 MB (base64 makes them about a
89
92
  third bigger). Smaller files can keep your existing path. PDFs under your payload limit are better
90
- sent inline, because Gemini reads their layout and images.
93
+ sent inline, because Gemini then reads every page with its layout and images. For larger PDFs,
94
+ turn on `keepOriginals` (below) so the model can ask for the pages it needs.
91
95
 
92
96
  ## 4. Answer questions
93
97
 
@@ -129,9 +133,12 @@ What `askGemini` does each turn:
129
133
 
130
134
  1. Measures the rest of the request (history, system prompt, other files).
131
135
  2. Plans the documents against your budget. Each one goes in whole, or becomes a card plus tools.
132
- 3. Adds each document's text or card to the last user message, and a short tool guide to the system prompt.
133
- 4. Runs the tool loop if needed (up to `maxToolTurns`, default 12). It always ends with a written
134
- answer, using a final tool-free turn if the model keeps searching.
136
+ 3. Adds each document's text or card at the start of the first user message, where it stays for
137
+ the whole conversation (so follow-up questions reuse Gemini's prompt cache), and a short tool
138
+ guide to the system prompt.
139
+ 4. Runs the tool loop if needed (up to `maxToolTurns` requests, default 12). If the model keeps
140
+ searching, the last request is sent without tools so it has to answer. `result.answered` is
141
+ `false` in the rare case that there is still no answer (a blocked prompt, or an empty reply).
135
142
 
136
143
  **Vertex AI:**
137
144
 
@@ -161,7 +168,31 @@ const endpoint = {
161
168
  Without `streamUrl`, answers arrive in one piece (and `onText` fires once).
162
169
 
163
170
  **Existing Gemini history.** If your chat already stores Gemini `contents` (with images or inline
164
- PDFs), pass `contents` instead of `messages`; document text is appended to the last user turn.
171
+ PDFs), pass `contents` instead of `messages`; document text is added at the start of the first user turn.
172
+
173
+ ### Pictures, charts and scans in PDFs
174
+
175
+ The text of a PDF does not hold its pictures. To let the model look at a page when the text is not
176
+ enough, install `@cantoo/pdf-lib` and keep the uploaded PDFs:
177
+
178
+ ```ts
179
+ export const files = createLargeFiles({
180
+ store: new FileDocumentStore("./data/large-files"),
181
+ keepOriginals: ["pdf"],
182
+ });
183
+ ```
184
+
185
+ `askGemini` needs no change. It offers the model a tool, `view_pages`, and sends the pages it asks
186
+ for (up to five a call) as a small PDF. A look shows up among the steps:
187
+
188
+ ```
189
+ ✓ Look at report.pdf pages 12-14
190
+ ```
191
+
192
+ With originals kept, a scanned PDF of up to 30 pages is accepted too, and read page by page.
193
+ Kept files take disk space until they expire, which is why this is off by default. The limits, the
194
+ costs and the measurements are in [Pictures in PDFs](configuration.md#pictures-in-pdfs), and what
195
+ to think about before turning it on in [Security](security.md#original-files).
165
196
 
166
197
  ### With another model: build your own loop
167
198
 
@@ -183,6 +214,9 @@ const tools = files.tools(prepared.plan.searchable, { generate: myTextCompletion
183
214
  `generate` is any `({ system, prompt, maxOutputTokens, signal }) => Promise<string>`. It's used
184
215
  only to read whole files in parts.
185
216
 
217
+ To offer `view_pages` in your own loop, it has to send a file to the model with a tool result. See
218
+ [Your own loop](configuration.md#your-own-loop).
219
+
186
220
  ## Keeping the conversation working
187
221
 
188
222
  - Send the **full history** each turn when files are attached. The plan is recomputed each time,