llm-large-files 0.2.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 (76) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +32 -6
  3. package/dist/extract.d.ts +13 -6
  4. package/dist/extract.d.ts.map +1 -1
  5. package/dist/extract.js +27 -6
  6. package/dist/extract.js.map +1 -1
  7. package/dist/gemini/chat.d.ts +16 -0
  8. package/dist/gemini/chat.d.ts.map +1 -1
  9. package/dist/gemini/chat.js +45 -11
  10. package/dist/gemini/chat.js.map +1 -1
  11. package/dist/gemini/generate.d.ts +34 -4
  12. package/dist/gemini/generate.d.ts.map +1 -1
  13. package/dist/gemini/generate.js +47 -7
  14. package/dist/gemini/generate.js.map +1 -1
  15. package/dist/gemini/index.d.ts +3 -3
  16. package/dist/gemini/index.d.ts.map +1 -1
  17. package/dist/gemini/index.js +2 -2
  18. package/dist/gemini/index.js.map +1 -1
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/library.d.ts +31 -1
  24. package/dist/library.d.ts.map +1 -1
  25. package/dist/library.js +44 -6
  26. package/dist/library.js.map +1 -1
  27. package/dist/pdf-layout.d.ts +7 -0
  28. package/dist/pdf-layout.d.ts.map +1 -1
  29. package/dist/pdf-layout.js +32 -2
  30. package/dist/pdf-layout.js.map +1 -1
  31. package/dist/pdf-pages.d.ts +45 -0
  32. package/dist/pdf-pages.d.ts.map +1 -0
  33. package/dist/pdf-pages.js +336 -0
  34. package/dist/pdf-pages.js.map +1 -0
  35. package/dist/pdf-pictures.d.ts +20 -0
  36. package/dist/pdf-pictures.d.ts.map +1 -0
  37. package/dist/pdf-pictures.js +336 -0
  38. package/dist/pdf-pictures.js.map +1 -0
  39. package/dist/plan.d.ts +13 -3
  40. package/dist/plan.d.ts.map +1 -1
  41. package/dist/plan.js +22 -17
  42. package/dist/plan.js.map +1 -1
  43. package/dist/search.d.ts +9 -0
  44. package/dist/search.d.ts.map +1 -1
  45. package/dist/search.js +41 -0
  46. package/dist/search.js.map +1 -1
  47. package/dist/stores.d.ts +7 -1
  48. package/dist/stores.d.ts.map +1 -1
  49. package/dist/stores.js +37 -5
  50. package/dist/stores.js.map +1 -1
  51. package/dist/tools.d.ts +11 -0
  52. package/dist/tools.d.ts.map +1 -1
  53. package/dist/tools.js +145 -13
  54. package/dist/tools.js.map +1 -1
  55. package/dist/types.d.ts +57 -3
  56. package/dist/types.d.ts.map +1 -1
  57. package/docs/api.md +39 -11
  58. package/docs/configuration.md +229 -5
  59. package/docs/getting-started.md +34 -3
  60. package/docs/how-it-works.md +52 -4
  61. package/docs/security.md +39 -4
  62. package/package.json +7 -2
  63. package/src/extract.ts +34 -8
  64. package/src/gemini/chat.ts +60 -13
  65. package/src/gemini/generate.ts +63 -9
  66. package/src/gemini/index.ts +3 -3
  67. package/src/index.ts +2 -2
  68. package/src/library.ts +74 -7
  69. package/src/pdf-layout.ts +37 -1
  70. package/src/pdf-pages.ts +315 -0
  71. package/src/pdf-pictures.ts +324 -0
  72. package/src/plan.ts +36 -16
  73. package/src/search.ts +37 -0
  74. package/src/stores.ts +39 -6
  75. package/src/tools.ts +147 -13
  76. package/src/types.ts +57 -3
package/docs/security.md CHANGED
@@ -24,7 +24,8 @@ can leak through logs, browser storage, or shared links.
24
24
  ## Tool scoping
25
25
 
26
26
  `files.tools(documents)` accepts only the IDs it was created with. A model (or a prompt injected
27
- into a file) can't reach another conversation's documents by naming their IDs.
27
+ into a file) can't reach another conversation's documents by naming their IDs. `view_pages` has
28
+ its own list, the PDFs passed as `viewPages`, and checks it the same way.
28
29
 
29
30
  ## Prompt injection
30
31
 
@@ -42,15 +43,49 @@ treat the model's output as untrusted.
42
43
  - Only IDs matching `doc_` plus 32 hex characters ever reach the file system, so there's no path
43
44
  traversal.
44
45
 
46
+ ## Original files
47
+
48
+ With `keepOriginals`, the uploaded file itself is stored next to its text (`<id>.bin` in
49
+ `FileDocumentStore`). That is off by default. When you turn it on:
50
+
51
+ - **More is kept than before.** The text of a PDF leaves out its pictures, signatures, stamps and
52
+ hidden layers; the file has them all, and its metadata (author, software, dates). Treat the
53
+ store as you treat the uploads themselves.
54
+ - **It follows the document.** The file has the document's owner and its expiry: it is returned
55
+ only to the owner (`files.getOriginal(id, { owner })`), it is gone for every reader once the
56
+ document has expired, and `delete` and `sweep` remove it from disk. A store of your own must do
57
+ the same in its `delete` and `sweep`.
58
+ - **It takes space.** Up to `maxUploadBytes` (100 MB) per document, for `ttlMs` (72 h). Lower
59
+ either, or sweep more often, if disk is short.
60
+ - **Pages go to the model.** `view_pages` sends the pages the model asks for to your model
61
+ provider, as the text of the file already goes. A PDF that is encrypted only to restrict printing
62
+ or copying is opened, and the cut is not encrypted: the restriction does not travel with it.
63
+
64
+ ## Reading PDFs for pages and pictures
65
+
66
+ Showing pages and marking pictures read the whole PDF into objects with `@cantoo/pdf-lib`, in your
67
+ process, on a file a user uploaded.
68
+
69
+ - **Memory.** About twice the size of the file, plus 1 to 1.6 KB for each object in it. A file of
70
+ 54 MB with 330,000 objects needed 700 MB. A file that declares more objects than the free heap
71
+ can hold, or more than a million, is refused before it is read (150,000 for the picture marks).
72
+ That check trusts what the file declares: a file that lies about it is still read.
73
+ - **Time, and no hard limit.** Reading cannot be interrupted once it has started. It pauses every
74
+ 4,000 objects so other requests get a turn, but a crafted file can hold the process: 1 MB of
75
+ junk between two objects took 3.6 seconds to skip. Errors are caught and the model is told that
76
+ the pages cannot be shown; a file that only takes long is not stopped.
77
+ - For uploads you do not trust, run ingest and the document tools in a worker thread or a separate
78
+ process with a memory limit and a timeout, as recommended for PDF text extraction below.
79
+
45
80
  ## Uploads
46
81
 
47
82
  - `maxUploadBytes` (default 100 MB) is enforced while reading, before the body is buffered fully.
48
83
  - The handlers buffer the upload in memory before extraction. Under heavy concurrent uploads, put a
49
84
  limit in front (a reverse proxy or a rate limiter).
50
85
  - Binary files are rejected, including compressed ones (`.gz`, `.zip`), which get a message
51
- telling the user to decompress first. PDF parsing runs `unpdf` (pdf.js) on untrusted input in
52
- your process. Keep it updated, or move extraction to a worker or sandbox for high-risk
53
- deployments.
86
+ telling the user to decompress first. PDF parsing runs `unpdf` (pdf.js), and with it installed
87
+ `@cantoo/pdf-lib`, on untrusted input in your process. Keep them updated, or move extraction to a
88
+ worker or sandbox for high-risk deployments.
54
89
  - File names are reduced to one printable line at ingest (no path, control characters, line
55
90
  breaks, or text-direction overrides) and quoted in the system instruction, so a name can't add
56
91
  lines to the prompt. The name is still text the model reads, like the file's content.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "llm-large-files",
3
- "version": "0.2.0",
4
- "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, and map-reduce. Gemini and Vertex AI helpers included.",
3
+ "version": "0.3.0",
4
+ "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, and a look at the pages of a PDF. Gemini and Vertex AI helpers included.",
5
5
  "keywords": [
6
6
  "llm",
7
7
  "gemini",
@@ -70,10 +70,14 @@
70
70
  "prepublishOnly": "npm run check"
71
71
  },
72
72
  "peerDependencies": {
73
+ "@cantoo/pdf-lib": "^2.11.1",
73
74
  "jszip": "^3.10.0",
74
75
  "unpdf": "^1.4.0"
75
76
  },
76
77
  "peerDependenciesMeta": {
78
+ "@cantoo/pdf-lib": {
79
+ "optional": true
80
+ },
77
81
  "jszip": {
78
82
  "optional": true
79
83
  },
@@ -82,6 +86,7 @@
82
86
  }
83
87
  },
84
88
  "devDependencies": {
89
+ "@cantoo/pdf-lib": "2.11.1",
85
90
  "@types/node": "^22.10.2",
86
91
  "jszip": "3.10.1",
87
92
  "typescript": "5.9.3",
package/src/extract.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { layoutPageText, plainPageText, type PdfTextItem } from "./pdf-layout.js";
2
- import type { DocumentFormat, ExtractedText, Extractor } from "./types.js";
1
+ import { layoutPage, plainPageText, type LayoutBox, type PdfTextItem } from "./pdf-layout.js";
2
+ import { findPicturePages, type PageGeometry } from "./pdf-pictures.js";
3
+ import type { DocumentFormat, ExtractedText, ExtractInput, Extractor } from "./types.js";
3
4
 
4
5
  const EXTENSION_FORMATS: Record<string, DocumentFormat> = {
5
6
  log: "log", out: "log", err: "log",
@@ -146,10 +147,21 @@ export type PdfExtractorOptions = {
146
147
  * in version 0.1.0.
147
148
  */
148
149
  tables?: boolean;
150
+ /**
151
+ * Write a line under the page header of every page that shows a picture or a drawing, so the
152
+ * model knows that the text does not tell all of that page. Defaults to true. It needs the
153
+ * optional dependency `@cantoo/pdf-lib`; without it, and with false, the text is that of 0.2.0.
154
+ */
155
+ pictures?: boolean;
149
156
  };
150
157
 
151
158
  /** Written in place of a page that has no text at all, so the model can say so instead of guessing. */
152
159
  const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or a chart.]";
160
+ /**
161
+ * Written under the header of a page that shows a picture or a drawing. The words hold whether or
162
+ * not the model is later given a way to look at the page.
163
+ */
164
+ export const PICTURE_ON_PAGE = "[Picture on this page. This text cannot show it.]";
153
165
 
154
166
  /**
155
167
  * The built-in PDF extractor (needs `unpdf`). Use it to change an option:
@@ -157,7 +169,8 @@ const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or
157
169
  */
158
170
  export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor {
159
171
  const tables = options.tables ?? true;
160
- return async (bytes) => {
172
+ const pictures = options.pictures ?? true;
173
+ return async (bytes, input) => {
161
174
  let unpdf: typeof import("unpdf");
162
175
  try {
163
176
  unpdf = await import("unpdf");
@@ -166,16 +179,19 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
166
179
  }
167
180
  // pdf.js may detach the buffer it reads, so give it a copy.
168
181
  const document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
169
- const pages: string[] = [];
182
+ const texts: string[] = [];
183
+ const geometry: PageGeometry[] = [];
170
184
  let hasText = false;
171
185
  for (let number = 1; number <= document.numPages; number++) {
172
186
  const page = await document.getPage(number);
173
187
  const content = await page.getTextContent();
174
188
  const items = (content.items as unknown[]).filter((item): item is PdfTextItem => typeof (item as PdfTextItem).str === "string");
189
+ const transform = page.getViewport({ scale: 1 }).transform as number[];
175
190
  let text = "";
191
+ let found: LayoutBox[] = [];
176
192
  if (tables) {
177
193
  try {
178
- text = layoutPageText(items, page.getViewport({ scale: 1 }).transform);
194
+ ({ text, tables: found } = layoutPage(items, transform));
179
195
  } catch {
180
196
  // Unusual geometry must never lose a page: fall back to the plain order.
181
197
  text = plainPageText(items);
@@ -185,12 +201,22 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
185
201
  }
186
202
  text = text.trim();
187
203
  if (text) hasText = true;
188
- pages.push(`--- Page ${number} ---\n${text || PAGE_WITHOUT_TEXT}`);
204
+ texts.push(text);
205
+ geometry.push({ view: page.view, transform, tables: found });
189
206
  page.cleanup();
190
207
  }
191
208
  if (!hasText) {
192
- throw new Error("This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.");
209
+ // A scan has nothing to search, but a short one can be read by looking at its pages, when the
210
+ // caller says that they can be shown. Every page then says that it has no text.
211
+ const most = input?.scannedPages ?? 0;
212
+ if (most <= 0) throw new Error("This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.");
213
+ if (document.numPages > most) {
214
+ throw new Error(`This PDF has no text layer (it may be scanned) and ${document.numPages} pages. Without text it can only be read by looking at its pages, which works for up to ${most} pages. It needs OCR first.`);
215
+ }
193
216
  }
217
+ // Which pages show a picture. Undefined when that could not be found out: then none is marked.
218
+ const pictured = pictures ? await findPicturePages(bytes, geometry) : undefined;
219
+ const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text || PAGE_WITHOUT_TEXT}`);
194
220
  return { text: pages.join("\n\n"), pages: document.numPages };
195
221
  };
196
222
  }
@@ -208,7 +234,7 @@ export const defaultExtractors: Record<DocumentFormat, Extractor> = {
208
234
 
209
235
  export async function extractText(
210
236
  bytes: Uint8Array,
211
- input: { name: string; mimeType: string; format: DocumentFormat },
237
+ input: ExtractInput,
212
238
  extractors: Partial<Record<DocumentFormat, Extractor>> = {},
213
239
  ): Promise<ExtractedText> {
214
240
  const extractor = extractors[input.format] ?? defaultExtractors[input.format];
@@ -1,9 +1,10 @@
1
1
  import type { LargeFiles } from "../library.js";
2
+ import { REQUEST_BYTES_MARGIN } from "../plan.js";
2
3
  import { estimateTokens, jsonBytes } from "../text.js";
3
- import { toolResultSummary } from "../tools.js";
4
- import type { DocumentPlan, ToolResult } from "../types.js";
4
+ import { TOOL_NAMES, toolResultSummary } from "../tools.js";
5
+ import type { DocumentPlan, ToolFile, ToolFileLimits, ToolResult } from "../types.js";
5
6
  import { resolveHeaders, type GeminiEndpoint } from "./endpoints.js";
6
- import { createGeminiGenerateText, geminiFunctionResponses, type GeminiFunctionCall } from "./generate.js";
7
+ import { createGeminiGenerateText, geminiFunctionResponseTurns, type GeminiFunctionCall, type GeminiToolFilePlacement } from "./generate.js";
7
8
  import { parseSseJson } from "./sse.js";
8
9
 
9
10
  export type GeminiPart = Record<string, unknown>;
@@ -13,6 +14,11 @@ export type ChatTurn = { role: "user" | "model" | "assistant"; text: string };
13
14
 
14
15
  /** Sent (invisibly to the user) when the model must stop using tools and answer. */
15
16
  export const FINAL_ANSWER_REQUEST = "Stop using tools now. Answer my question using only what the tools returned above, with line citations. Say plainly what you could not find.";
17
+ /** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
18
+ export const FINAL_ANSWER_AFTER_PAGES = "Stop using tools now. Answer my question from the text of the files and the pages you looked at. Say plainly what you could not see or find.";
19
+
20
+ /** What Gemini bills for one PDF page it is shown (measured: 520 to 532). */
21
+ const PAGE_TOKENS = 530;
16
22
 
17
23
  /** Some document IDs were never uploaded, have expired, or belong to another owner. */
18
24
  export class DocumentsNotFoundError extends Error {
@@ -59,6 +65,19 @@ export type AskGeminiOptions = {
59
65
  maxToolTurns?: number;
60
66
  /** Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true. */
61
67
  wholeDocumentAnalysis?: boolean;
68
+ /**
69
+ * Offer `view_pages` for PDFs whose original file is kept (`keepOriginals`), so the model can
70
+ * look at pictures, charts and layout. Defaults to true. It changes nothing for a library that
71
+ * keeps no originals.
72
+ */
73
+ viewPages?: boolean;
74
+ /**
75
+ * Where the pages go in the request. "inside" (the default) puts the PDF in the function
76
+ * response itself, which Gemini 3 models read. "beside" sends it in a user turn of its own,
77
+ * after the function responses: use it for Gemini 2.5, which does not see a file inside a
78
+ * function response.
79
+ */
80
+ toolFilePlacement?: GeminiToolFilePlacement;
62
81
  /** generationConfig for whole-document part reads. Defaults to `{ temperature: 0.2, maxOutputTokens }`. */
63
82
  analysisConfig?: (maxOutputTokens: number) => Record<string, unknown>;
64
83
  /** Answer text as it streams. Streaming is used when this is set and the endpoint has `streamUrl`. */
@@ -144,7 +163,7 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
144
163
  const fetchImpl = options.fetch ?? fetch;
145
164
  const { files, endpoint, signal } = options;
146
165
  const contents = toContents(options);
147
- const prepared = await files.prepare(options.documentIds, baseSize(contents, options.system), { owner: options.owner });
166
+ const prepared = await files.prepare(options.documentIds, baseSize(contents, options.system), { owner: options.owner, viewPages: options.viewPages !== false });
148
167
  if (prepared.missing.length) throw new DocumentsNotFoundError(prepared.missing);
149
168
 
150
169
  const blocks = [...new Set(options.documentIds)].map((id) => prepared.blocks.get(id)).filter((block): block is string => Boolean(block));
@@ -238,18 +257,30 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
238
257
  ...(usage ? { usage } : {}),
239
258
  });
240
259
 
241
- if (prepared.plan.searchable.length === 0) return result((await turn()).wroteText);
260
+ // Tools are needed for a file that is too large to send whole, and for a PDF whose pages can be
261
+ // looked at: that one may have its whole text in the prompt and still hide a chart from the model.
262
+ const { searchable } = prepared.plan;
263
+ const { viewable } = prepared;
264
+ if (searchable.length === 0 && viewable.length === 0) return result((await turn()).wroteText);
242
265
 
243
- const tools = files.tools(prepared.plan.searchable, {
266
+ const tools = files.tools(searchable, {
244
267
  ...(options.wholeDocumentAnalysis === false ? {} : {
245
268
  generate: createGeminiGenerateText({ url: endpoint.url, headers, fetchImpl, ...(options.analysisConfig ? { generationConfig: options.analysisConfig } : {}) }),
246
269
  }),
247
270
  onProgress: (event) => options.onActivity?.(`${event.message}…`),
248
271
  ...(signal ? { signal } : {}),
272
+ ...(viewable.length > 0 ? { viewPages: viewable } : {}),
249
273
  });
250
274
  body.tools = [{ functionDeclarations: tools.declarations }];
251
275
  body.toolConfig = { functionCallingConfig: { mode: "AUTO" } };
252
- options.onActivity?.(`Too large to read at once: ${prepared.plan.searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
276
+ if (searchable.length > 0) options.onActivity?.(`Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
277
+
278
+ // Pages the model looks at stay in the request until the question is answered, so they are
279
+ // counted twice: as bytes against the request limit, and as tokens against half of what the
280
+ // budget keeps free for tool results and the answer.
281
+ const { maxRequestBytes, reservedTokens } = files.budget;
282
+ const bytesKeptFree = Math.max(REQUEST_BYTES_MARGIN, Math.floor(maxRequestBytes / 10));
283
+ let pagesLeft = Math.floor(reservedTokens / 2 / PAGE_TOKENS);
253
284
 
254
285
  const maxTurns = Math.max(1, options.maxToolTurns ?? 12);
255
286
  let answered = false;
@@ -263,17 +294,27 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
263
294
  break;
264
295
  }
265
296
  body.contents.push({ role: "model", parts });
266
- const responses: Array<{ call: GeminiFunctionCall; result: ToolResult }> = [];
297
+ const responses: Array<{ call: GeminiFunctionCall; result: ToolResult; files: ToolFile[] }> = [];
298
+ // The size of the request as it stands, worked out when the first look at pages in this turn needs it.
299
+ let requestBytes: number | undefined;
267
300
  for (const call of calls) {
268
301
  const label = tools.has(call.name) ? tools.describe(call.name, call.args) : call.name;
269
302
  options.onActivity?.(`${label}…`);
270
- const output = await tools.execute(call.name, call.args);
271
- const step = `${label}${toolResultSummary(label, output)}`;
303
+ let limits: ToolFileLimits | undefined;
304
+ if (call.name === TOOL_NAMES.view) {
305
+ requestBytes ??= Buffer.byteLength(JSON.stringify(body));
306
+ // Base64 turns three bytes into four characters.
307
+ limits = { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft };
308
+ }
309
+ const output = await tools.executeWithFiles(call.name, call.args, limits);
310
+ for (const file of output.files) requestBytes = (requestBytes ?? 0) + Math.ceil(file.bytes.length / 3) * 4 + 512;
311
+ if (output.files.length > 0) pagesLeft -= pagesShown(output.result);
312
+ const step = `${label}${toolResultSummary(label, output.result)}`;
272
313
  steps.push(step);
273
314
  options.onStep?.(step);
274
- responses.push({ call, result: { ...output, tool_turns_left: maxTurns - round - 1 } });
315
+ responses.push({ call, result: { ...output.result, tool_turns_left: maxTurns - round - 1 }, files: output.files });
275
316
  }
276
- body.contents.push(geminiFunctionResponses(responses) as GeminiContent);
317
+ body.contents.push(...geminiFunctionResponseTurns(responses, { files: options.toolFilePlacement ?? "inside" }) as GeminiContent[]);
277
318
  }
278
319
 
279
320
  // Out of tool turns, or the last turn had no text (cut off, or a malformed tool call): ask once
@@ -283,8 +324,14 @@ export async function askGemini(options: AskGeminiOptions): Promise<AskGeminiRes
283
324
  options.onActivity?.("Writing the answer…");
284
325
  delete body.tools;
285
326
  delete body.toolConfig;
286
- body.contents.push({ role: "user", parts: [{ text: FINAL_ANSWER_REQUEST }] });
327
+ body.contents.push({ role: "user", parts: [{ text: searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES }] });
287
328
  answered = (await turn()).wroteText;
288
329
  }
289
330
  return result(answered);
290
331
  }
332
+
333
+ /** How many pages a `view_pages` result showed: its `pages` is "12" or "12-14". */
334
+ function pagesShown(result: ToolResult): number {
335
+ const [first, last] = String(result.pages ?? "").split("-").map(Number);
336
+ return Number.isFinite(first) ? (Number.isFinite(last) ? last! - first! + 1 : 1) : 0;
337
+ }
@@ -1,6 +1,6 @@
1
1
  // Gemini (Generate Content REST) helpers. No SDK dependency: the caller supplies the URL and
2
2
  // auth headers, so this works with the Gemini API, Vertex AI, or an enterprise gateway.
3
- import type { GenerateText, ToolDeclaration, ToolResult } from "../types.js";
3
+ import type { GenerateText, ToolDeclaration, ToolFile, ToolResult } from "../types.js";
4
4
 
5
5
  /** Gemini accepts this package's JSON Schema subset as-is. */
6
6
  export function toGeminiTools(declarations: ToolDeclaration[]): { functionDeclarations: ToolDeclaration[] } {
@@ -9,14 +9,68 @@ export function toGeminiTools(declarations: ToolDeclaration[]): { functionDeclar
9
9
 
10
10
  export type GeminiFunctionCall = { name: string; args: Record<string, unknown>; id?: string };
11
11
 
12
- /** The `user` turn that answers a model turn's function calls, in call order. */
13
- export function geminiFunctionResponses(calls: Array<{ call: GeminiFunctionCall; result: ToolResult }>): { role: "user"; parts: unknown[] } {
14
- return {
15
- role: "user",
16
- parts: calls.map(({ call, result }) => ({
17
- functionResponse: { name: call.name, ...(call.id ? { id: call.id } : {}), response: result },
18
- })),
19
- };
12
+ /**
13
+ * Where a file that a tool returned goes in the request:
14
+ * - "inside": in the `parts` of its function response, which names it with `{ "$ref": name }`
15
+ * (Gemini 3 multimodal function responses). Gemini 2.5 accepts that form and does not see the
16
+ * file.
17
+ * - "beside": in a `user` turn of its own, after the turn of function responses, for a model that
18
+ * does not read a file inside a function response.
19
+ */
20
+ export type GeminiToolFilePlacement = "inside" | "beside";
21
+
22
+ /** A function call of the model with what the tool returned for it. */
23
+ export type GeminiToolAnswer = { call: GeminiFunctionCall; result: ToolResult; files?: ToolFile[] };
24
+
25
+ type UserTurn = { role: "user"; parts: unknown[] };
26
+
27
+ const base64 = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
28
+
29
+ /** One function response, with `files` inside it. */
30
+ function functionResponse(call: GeminiFunctionCall, result: ToolResult, files: ToolFile[]): unknown {
31
+ let response = result;
32
+ const parts: unknown[] = [];
33
+ if (files.length > 0) {
34
+ // The result names its file ("file": "pages-2-3.pdf"); that becomes the reference Gemini resolves.
35
+ response = { ...result };
36
+ const unnamed: Array<{ $ref: string }> = [];
37
+ for (const file of files) {
38
+ const named = Object.keys(response).find((key) => response[key] === file.name);
39
+ if (named) response[named] = { $ref: file.name };
40
+ else unnamed.push({ $ref: file.name });
41
+ parts.push({ inlineData: { mimeType: file.mimeType, displayName: file.name, data: base64(file.bytes) } });
42
+ }
43
+ if (unnamed.length > 0) response.files = unnamed;
44
+ }
45
+ return { functionResponse: { name: call.name, ...(call.id ? { id: call.id } : {}), response, ...(parts.length > 0 ? { parts } : {}) } };
46
+ }
47
+
48
+ /**
49
+ * The `user` turn that answers a model turn's function calls, in call order. A file that a tool
50
+ * returned (`executeWithFiles`) goes inside its function response, as base64 `inlineData`. To send
51
+ * files beside the function responses instead, use `geminiFunctionResponseTurns`.
52
+ */
53
+ export function geminiFunctionResponses(calls: GeminiToolAnswer[]): UserTurn {
54
+ return { role: "user", parts: calls.map(({ call, result, files = [] }) => functionResponse(call, result, files)) };
55
+ }
56
+
57
+ /**
58
+ * The turns that answer a model turn's function calls: add them all to `contents`, in order.
59
+ * With files "inside" (the default) that is the one turn of `geminiFunctionResponses`. With files
60
+ * "beside", the function responses carry no file and a second `user` turn holds the files, each
61
+ * after a line that names it and the tool it came from.
62
+ *
63
+ * The files get a turn of their own because Vertex AI refuses a turn in which anything follows a
64
+ * function response (HTTP 400 for Gemini 3 models, November 2026).
65
+ */
66
+ export function geminiFunctionResponseTurns(calls: GeminiToolAnswer[], options: { files?: GeminiToolFilePlacement } = {}): UserTurn[] {
67
+ if (options.files !== "beside") return [geminiFunctionResponses(calls)];
68
+ const responses = calls.map(({ call, result }) => functionResponse(call, result, []));
69
+ const files = calls.flatMap(({ call, files: returned = [] }) => returned.flatMap((file) => [
70
+ { text: `${file.name} (returned by ${call.name}):` },
71
+ { inlineData: { mimeType: file.mimeType, data: base64(file.bytes) } },
72
+ ]));
73
+ return [{ role: "user", parts: responses }, ...(files.length > 0 ? [{ role: "user" as const, parts: files }] : [])];
20
74
  }
21
75
 
22
76
  /**
@@ -1,7 +1,7 @@
1
- export { askGemini, DocumentsNotFoundError, FINAL_ANSWER_REQUEST, GeminiRequestError } from "./chat.js";
1
+ export { askGemini, DocumentsNotFoundError, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, GeminiRequestError } from "./chat.js";
2
2
  export type { AskGeminiOptions, AskGeminiResult, ChatTurn, GeminiContent, GeminiPart } from "./chat.js";
3
3
  export { geminiApi, vertexAi, vertexHost } from "./endpoints.js";
4
4
  export type { GeminiEndpoint } from "./endpoints.js";
5
- export { createGeminiGenerateText, geminiFunctionResponses, toGeminiTools } from "./generate.js";
6
- export type { GeminiFunctionCall } from "./generate.js";
5
+ export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, toGeminiTools } from "./generate.js";
6
+ export type { GeminiFunctionCall, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
7
7
  export { parseSseJson } from "./sse.js";
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  // Core: provider-neutral. Gemini helpers live in "llm-large-files/gemini",
2
2
  // Node HTTP handlers in "llm-large-files/node".
3
3
  export { createLargeFiles, DEFAULT_BUDGET, isDocumentId, toDocumentSummary } from "./library.js";
4
- export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, ToolOptions } from "./library.js";
4
+ export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, PrepareOptions, ToolOptions } from "./library.js";
5
5
  export { FileDocumentStore, MemoryDocumentStore, DOCUMENT_ID_PATTERN } from "./stores.js";
6
6
  export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
7
7
  export type { PdfExtractorOptions } from "./extract.js";
8
8
  export { estimateTokens, utf8Bytes, jsonBytes } from "./text.js";
9
- export { TOOL_NAMES, toolResultSummary } from "./tools.js";
9
+ export { MAX_VIEW_PAGES, TOOL_NAMES, toolResultSummary } from "./tools.js";
10
10
  export type * from "./types.js";
package/src/library.ts CHANGED
@@ -41,6 +41,18 @@ export type LargeFilesOptions = {
41
41
  maxUploadBytes?: number;
42
42
  /** Override or add text extractors per format. */
43
43
  extractors?: Partial<Record<DocumentFormat, Extractor>>;
44
+ /**
45
+ * Formats whose uploaded file is kept in the store next to its text, for example `["pdf"]`.
46
+ * Empty by default: a kept file takes disk space, up to the upload limit, until the document
47
+ * expires. A store without `putOriginal` keeps none.
48
+ */
49
+ keepOriginals?: DocumentFormat[];
50
+ /**
51
+ * A PDF without any text (a scan) has nothing to search, and was always refused. When its
52
+ * original is kept, its pages can be shown to the model instead, so one of up to this many pages
53
+ * is accepted. Defaults to 30. 0 refuses every PDF without text, as before.
54
+ */
55
+ scannedPdfPages?: number;
44
56
  /** How many parsed documents to keep in memory for repeated tool calls. Defaults to 6. */
45
57
  cacheSize?: number;
46
58
  /** Clock override, for tests. */
@@ -58,12 +70,29 @@ export type IngestInput = {
58
70
  /** Access options. When a document has an owner, only that owner can use it. */
59
71
  export type AccessOptions = { owner?: string };
60
72
 
73
+ export type PrepareOptions = AccessOptions & {
74
+ /**
75
+ * Say that your tool loop can pass files to the model (see `ToolOptions.viewPages`). The result
76
+ * then lists the PDFs whose pages can be shown in `viewable`, and the instruction and the cards
77
+ * tell the model about `view_pages`. Without it, the result is that of 0.2.0.
78
+ */
79
+ viewPages?: boolean;
80
+ };
81
+
61
82
  export type ToolOptions = {
62
83
  /** Enables `analyze_whole_document`, which reads the entire file in parts. */
63
84
  generate?: GenerateText;
64
85
  /** Progress of whole-document reads, for status messages. */
65
86
  onProgress?: ProgressListener;
66
87
  signal?: AbortSignal;
88
+ /**
89
+ * Offers `view_pages`, which hands the model real pages of a PDF whose original file is kept
90
+ * (see `keepOriginals`). The pages come back as a file, so turn this on only when your loop
91
+ * runs tools with `executeWithFiles` and sends the files to the model. `true` offers it for the
92
+ * documents passed to `tools`; a list offers it for exactly those documents, which may include
93
+ * PDFs that are not searched because their text is already in the prompt.
94
+ */
95
+ viewPages?: boolean | DocumentMeta[];
67
96
  };
68
97
 
69
98
  export interface LargeFiles {
@@ -73,6 +102,8 @@ export interface LargeFiles {
73
102
  /** Extracts, normalizes, profiles, and stores a file. Throws a user-readable Error on bad input. */
74
103
  ingest(input: IngestInput): Promise<DocumentMeta>;
75
104
  getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
105
+ /** The uploaded file itself, when it was kept (see `keepOriginals`). Treat the bytes as read-only. */
106
+ getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>;
76
107
  delete(id: string, access?: AccessOptions): Promise<boolean>;
77
108
  /** Removes expired documents from the store. Returns how many were removed. */
78
109
  sweep(): Promise<number>;
@@ -80,7 +111,7 @@ export interface LargeFiles {
80
111
  * Plans one model request: which documents go in whole and which become searchable cards.
81
112
  * `base` is the size of everything else in the request (messages, system prompt, other files).
82
113
  */
83
- prepare(ids: string[], base: { tokens: number; bytes: number }, access?: AccessOptions): Promise<PreparedContext>;
114
+ prepare(ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext>;
84
115
  /** Tools scoped to these documents. Pass `generate` to enable whole-document analysis. */
85
116
  tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
86
117
  }
@@ -130,6 +161,10 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
130
161
  const now = options.now ?? (() => new Date());
131
162
  const cacheSize = Math.max(1, options.cacheSize ?? 6);
132
163
  const cache = new Map<string, SearchableDocument>();
164
+ const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
165
+ const scannedPdfPages = Math.max(0, Math.trunc(options.scannedPdfPages ?? 30));
166
+ /** Whether the uploaded file of a document of this format is kept. */
167
+ const keeps = (format: DocumentFormat) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
133
168
 
134
169
  async function load(id: string): Promise<SearchableDocument | undefined> {
135
170
  const cached = cache.get(id);
@@ -168,13 +203,20 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
168
203
  throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
169
204
  }
170
205
  let format = detectFormat(name, mimeType);
171
- const extracted = await extractText(input.bytes, { name, mimeType, format }, options.extractors);
206
+ const extracted = await extractText(input.bytes, {
207
+ name,
208
+ mimeType,
209
+ format,
210
+ // A scan is worth storing only if its pages can be shown later: that needs the file itself.
211
+ ...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
212
+ }, options.extractors);
172
213
  const { text, wrapped } = wrapLongLines(normalizeText(extracted.text));
173
214
  if (!text.trim()) throw new Error(`${name} did not contain any text.`);
174
215
  const lines = text.split("\n");
175
216
  if (text.endsWith("\n")) lines.pop();
176
217
  if (format === "text" && looksLikeLog(lines)) format = "log";
177
218
  const created = now();
219
+ const keepOriginal = keeps(format);
178
220
  const meta: DocumentMeta = {
179
221
  id: `doc_${randomUUID().replaceAll("-", "")}`,
180
222
  ...(input.owner !== undefined ? { owner: input.owner } : {}),
@@ -188,17 +230,31 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
188
230
  estimatedTokens: estimateTokens(text),
189
231
  wrappedLines: wrapped,
190
232
  ...(extracted.pages ? { pages: extracted.pages } : {}),
233
+ ...(keepOriginal ? { originalKept: true } : {}),
191
234
  outline: buildOutline(lines, format),
192
235
  ...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
193
236
  createdAt: created.toISOString(),
194
237
  expiresAt: new Date(created.getTime() + ttlMs).toISOString(),
195
238
  };
196
- await options.store.put({ meta, text });
239
+ try {
240
+ // The file first, the document last: a document is there once its metadata is.
241
+ if (keepOriginal) await options.store.putOriginal!(meta.id, input.bytes);
242
+ await options.store.put({ meta, text });
243
+ } catch (error) {
244
+ // Do not leave a file of up to the upload limit behind for a document that does not exist.
245
+ if (keepOriginal) await options.store.delete(meta.id).catch(() => undefined);
246
+ throw error;
247
+ }
197
248
  return meta;
198
249
  },
199
250
 
200
251
  getMeta: metaFor,
201
252
 
253
+ async getOriginal(id, access) {
254
+ const meta = await metaFor(id, access);
255
+ return meta?.originalKept ? options.store.getOriginal?.(id) : undefined;
256
+ },
257
+
202
258
  async delete(id, access) {
203
259
  if (!await metaFor(id, access)) return false;
204
260
  cache.delete(id);
@@ -221,20 +277,31 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
221
277
  }
222
278
  const plan = planDocuments(documents.map((document) => document.meta), budget, base);
223
279
  const inline = new Set(plan.inline.map((meta) => meta.id));
280
+ // Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
281
+ const viewable = access?.viewPages && options.store.getOriginal
282
+ ? documents.map((document) => document.meta).filter((meta) => meta.format === "pdf" && meta.originalKept)
283
+ : [];
284
+ const shown = new Set(viewable.map((meta) => meta.id));
224
285
  const blocks = new Map<string, string>();
225
286
  for (const document of documents) {
226
- blocks.set(document.meta.id, inline.has(document.meta.id) ? renderInline(document) : renderCard(document));
287
+ const { id } = document.meta;
288
+ blocks.set(id, inline.has(id) ? renderInline(document) : renderCard(document, shown.has(id)));
227
289
  }
228
- return { plan, blocks, instruction: documentToolsInstruction(plan.searchable), missing };
290
+ return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable), missing, viewable };
229
291
  },
230
292
 
231
293
  tools(documents, toolOptions = {}) {
294
+ const { viewPages, ...rest } = toolOptions;
295
+ const loadOriginal = options.store.getOriginal?.bind(options.store);
296
+ const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
297
+ .filter((meta) => meta.format === "pdf" && meta.originalKept);
232
298
  return createDocumentTools({
233
299
  load,
234
300
  documentIds: documents.map((meta) => meta.id),
235
- names: Object.fromEntries(documents.map((meta) => [meta.id, meta.name])),
301
+ names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, meta.name])),
236
302
  budget,
237
- ...toolOptions,
303
+ ...(loadOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal } : {}),
304
+ ...rest,
238
305
  });
239
306
  },
240
307
  };