llm-large-files 0.2.0 → 0.3.5
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.
- package/CHANGELOG.md +101 -0
- package/README.md +52 -6
- package/dist/extract.d.ts +13 -6
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +27 -6
- package/dist/extract.js.map +1 -1
- package/dist/gemini/chat.d.ts +48 -4
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +108 -24
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +17 -0
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +16 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/generate.d.ts +34 -4
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +47 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +31 -1
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +44 -6
- package/dist/library.js.map +1 -1
- package/dist/pdf-layout.d.ts +7 -0
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +32 -2
- package/dist/pdf-layout.js.map +1 -1
- package/dist/pdf-pages.d.ts +45 -0
- package/dist/pdf-pages.d.ts.map +1 -0
- package/dist/pdf-pages.js +336 -0
- package/dist/pdf-pages.js.map +1 -0
- package/dist/pdf-pictures.d.ts +20 -0
- package/dist/pdf-pictures.d.ts.map +1 -0
- package/dist/pdf-pictures.js +336 -0
- package/dist/pdf-pictures.js.map +1 -0
- package/dist/plan.d.ts +13 -3
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +22 -17
- package/dist/plan.js.map +1 -1
- package/dist/search.d.ts +9 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +41 -0
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +7 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +37 -5
- package/dist/stores.js.map +1 -1
- package/dist/tools.d.ts +11 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +145 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +57 -3
- package/dist/types.d.ts.map +1 -1
- package/docs/api.md +59 -17
- package/docs/configuration.md +351 -5
- package/docs/getting-started.md +50 -3
- package/docs/how-it-works.md +73 -4
- package/docs/security.md +39 -4
- package/package.json +7 -2
- package/src/extract.ts +34 -8
- package/src/gemini/chat.ts +145 -30
- package/src/gemini/endpoints.ts +34 -2
- package/src/gemini/generate.ts +63 -9
- package/src/gemini/index.ts +3 -3
- package/src/index.ts +2 -2
- package/src/library.ts +74 -7
- package/src/pdf-layout.ts +37 -1
- package/src/pdf-pages.ts +315 -0
- package/src/pdf-pictures.ts +324 -0
- package/src/plan.ts +36 -16
- package/src/search.ts +37 -0
- package/src/stores.ts +39 -6
- package/src/tools.ts +147 -13
- package/src/types.ts +57 -3
package/docs/getting-started.md
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
|
@@ -166,6 +170,46 @@ Without `streamUrl`, answers arrive in one piece (and `onText` fires once).
|
|
|
166
170
|
**Existing Gemini history.** If your chat already stores Gemini `contents` (with images or inline
|
|
167
171
|
PDFs), pass `contents` instead of `messages`; document text is added at the start of the first user turn.
|
|
168
172
|
|
|
173
|
+
**A second model for the searching (optional).** The model you name does both halves of the work:
|
|
174
|
+
it searches and reads a large file, and it answers. `explorerModel` gives the first half to another
|
|
175
|
+
model, for example a cheaper one, and `model` then only writes the answer:
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
const endpoint = geminiApi({
|
|
179
|
+
apiKey: process.env.GEMINI_API_KEY!,
|
|
180
|
+
model: "gemini-3.8-flash",
|
|
181
|
+
explorerModel: process.env.GEMINI_EXPLORER_MODEL, // unset or empty: one model does both
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
`vertexAi()` takes it the same way, and an endpoint of your own takes the explorer's URL as
|
|
186
|
+
`explorerUrl`. What each model gets, and what it costs, is in
|
|
187
|
+
[An explorer model](configuration.md#an-explorer-model).
|
|
188
|
+
|
|
189
|
+
### Pictures, charts and scans in PDFs
|
|
190
|
+
|
|
191
|
+
The text of a PDF does not hold its pictures. To let the model look at a page when the text is not
|
|
192
|
+
enough, install `@cantoo/pdf-lib` and keep the uploaded PDFs:
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
export const files = createLargeFiles({
|
|
196
|
+
store: new FileDocumentStore("./data/large-files"),
|
|
197
|
+
keepOriginals: ["pdf"],
|
|
198
|
+
});
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`askGemini` needs no change. It offers the model a tool, `view_pages`, and sends the pages it asks
|
|
202
|
+
for (up to five a call) as a small PDF. A look shows up among the steps:
|
|
203
|
+
|
|
204
|
+
```
|
|
205
|
+
✓ Look at report.pdf pages 12-14
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
With originals kept, a scanned PDF of up to 30 pages is accepted too, and read page by page.
|
|
209
|
+
Kept files take disk space until they expire, which is why this is off by default. The limits, the
|
|
210
|
+
costs and the measurements are in [Pictures in PDFs](configuration.md#pictures-in-pdfs), and what
|
|
211
|
+
to think about before turning it on in [Security](security.md#original-files).
|
|
212
|
+
|
|
169
213
|
### With another model: build your own loop
|
|
170
214
|
|
|
171
215
|
`files.prepare()` and `files.tools()` are provider-neutral. Tool declarations are plain JSON Schema,
|
|
@@ -186,6 +230,9 @@ const tools = files.tools(prepared.plan.searchable, { generate: myTextCompletion
|
|
|
186
230
|
`generate` is any `({ system, prompt, maxOutputTokens, signal }) => Promise<string>`. It's used
|
|
187
231
|
only to read whole files in parts.
|
|
188
232
|
|
|
233
|
+
To offer `view_pages` in your own loop, it has to send a file to the model with a tool result. See
|
|
234
|
+
[Your own loop](configuration.md#your-own-loop).
|
|
235
|
+
|
|
189
236
|
## Keeping the conversation working
|
|
190
237
|
|
|
191
238
|
- Send the **full history** each turn when files are attached. The plan is recomputed each time,
|
package/docs/how-it-works.md
CHANGED
|
@@ -2,26 +2,33 @@
|
|
|
2
2
|
|
|
3
3
|
```
|
|
4
4
|
upload ─► ingest ─► store extract text · normalize · index lines · outline · log profile
|
|
5
|
-
│
|
|
5
|
+
│ (and the uploaded file itself, for formats in keepOriginals)
|
|
6
6
|
chat turn ─► prepare(ids, size of the rest of the request)
|
|
7
7
|
├─ fits ────► full text in the prompt
|
|
8
8
|
└─ too big ─► summary card in the prompt
|
|
9
9
|
+ tool guide in the system prompt
|
|
10
10
|
+ tools: search · read · overview · analyze-all
|
|
11
|
+
a PDF whose file is kept, in either branch
|
|
12
|
+
─► + tool: view_pages (the real pages, as a small PDF)
|
|
11
13
|
```
|
|
12
14
|
|
|
13
15
|
## Ingest
|
|
14
16
|
|
|
15
17
|
1. **Extract** text by format (built-in extractors or your own). In a PDF, tables are rebuilt from
|
|
16
18
|
the position of their text and written as `| cell | cell | |` rows, so an empty cell stays an
|
|
17
|
-
empty cell ([details and limits](configuration.md#pdf-tables)).
|
|
19
|
+
empty cell ([details and limits](configuration.md#pdf-tables)). A page that shows a picture or a
|
|
20
|
+
drawing gets a line that says so. Those pages are found from the structure of the file: a small
|
|
21
|
+
interpreter follows each page's drawing instructions and notes where images are painted and
|
|
22
|
+
which shapes are filled, without decoding any image
|
|
23
|
+
([what counts](configuration.md#the-line-that-marks-a-page)).
|
|
18
24
|
2. **Normalize**: strip the BOM, unify line endings, remove terminal colour codes and control
|
|
19
25
|
characters, split lines over 2,000 characters.
|
|
20
26
|
3. **Profile**: count lines, estimate tokens and UTF-8 bytes, and build an outline (headings with
|
|
21
27
|
line numbers). For logs, also count levels, find the time range, and group ERROR/FATAL/WARN lines
|
|
22
28
|
by *shape*. Numbers, IDs, IPs, hex, and quoted values are replaced with placeholders, so 800
|
|
23
29
|
timeouts to different hosts become one entry: `[ERROR ×812, L1203] timeout after <n>ms to <ip>`.
|
|
24
|
-
4. **Store** the text and metadata
|
|
30
|
+
4. **Store** the text and metadata, and the uploaded file when its format is in `keepOriginals`.
|
|
31
|
+
Nothing else is indexed up front.
|
|
25
32
|
|
|
26
33
|
## The card
|
|
27
34
|
|
|
@@ -44,9 +51,39 @@ FATAL line listed on the card.
|
|
|
44
51
|
- **`get_document_overview`**: the full outline and profile, the first and last lines, and how many
|
|
45
52
|
parts a whole-file read would take.
|
|
46
53
|
- **`analyze_whole_document`**: map-reduce (below).
|
|
54
|
+
- **`view_pages`**: pages of a PDF, cut out of the kept original into a PDF of their own
|
|
55
|
+
(below). It is the only tool that returns a file.
|
|
47
56
|
|
|
48
57
|
Every result is capped (`toolResultCharacters`) and states what was cut, so one tool call can never
|
|
49
|
-
overflow the request.
|
|
58
|
+
overflow the request. `view_pages` is capped in pages and in bytes instead.
|
|
59
|
+
|
|
60
|
+
## Looking at pages
|
|
61
|
+
|
|
62
|
+
Text cannot show a chart. `view_pages(document_id, from_page, to_page)` gives the model the pages
|
|
63
|
+
themselves: up to five a call, as one PDF, which Gemini reads like any PDF.
|
|
64
|
+
|
|
65
|
+
Cutting pages out of a PDF sounds like copying them. Copied the way PDF libraries offer it, a page
|
|
66
|
+
brings along everything it refers to:
|
|
67
|
+
|
|
68
|
+
- **Links.** A contents page links to every section. Each link holds a reference to its target
|
|
69
|
+
page, so the copy took those pages too, with their pictures: the contents page of a 7.5 MB report
|
|
70
|
+
came out at 6.7 MB. Before copying, every page that is not wanted is replaced by an empty one, so
|
|
71
|
+
a reference to it costs a few bytes. The same contents page is then 55 KB.
|
|
72
|
+
- **Shared resources.** FPDF, TCPDF, jsPDF and others write one list of all images of the file and
|
|
73
|
+
give it to every page. A copy of one page carried all of them. The content of each wanted page is
|
|
74
|
+
read to see which images it paints, and the page gets a list of only those. Nothing is dropped
|
|
75
|
+
unless all content that could name an image was read.
|
|
76
|
+
- **Layers.** A file can hide a layer. The settings that say so are copied with the pages, or the
|
|
77
|
+
hidden layer would show.
|
|
78
|
+
|
|
79
|
+
The pages are counted against the request twice. As bytes: base64 makes them a third larger, and
|
|
80
|
+
they stay in the request until the question is answered, so the room for the next look shrinks.
|
|
81
|
+
As tokens: about 530 a page, against half of `reservedTokens`. When either runs out, the tool says
|
|
82
|
+
so and the model answers from what it has
|
|
83
|
+
([limits and measurements](configuration.md#view_pages)).
|
|
84
|
+
|
|
85
|
+
A PDF whose text fits in the prompt gets `view_pages` too, and only that. Such a file is often a
|
|
86
|
+
slide deck: little text, a picture on every page.
|
|
50
87
|
|
|
51
88
|
## Map-reduce
|
|
52
89
|
|
|
@@ -84,6 +121,35 @@ Jobs needing more than `maxMapChunks` parts are refused, with advice to narrow t
|
|
|
84
121
|
calls would be thrown away.
|
|
85
122
|
- If even that request has no text, or Gemini blocks the prompt, the result has `answered: false`
|
|
86
123
|
(and `blockReason`), so the caller can show its own message instead of an empty answer.
|
|
124
|
+
- Pages from `view_pages` go **inside the function response** (`functionResponse.parts`, with the
|
|
125
|
+
result naming the file as `{ "$ref": "pages-12-14.pdf" }`). `toolFilePlacement: "beside"` sends
|
|
126
|
+
them in a `user` turn of their own, right after the turn of function responses: Gemini 2.5 does
|
|
127
|
+
not see a file inside a function response. The files do not share a turn with the function
|
|
128
|
+
responses, because Vertex AI refuses a turn in which anything follows one. Both forms work with
|
|
129
|
+
Gemini 3.5 on the Gemini API and on Vertex AI.
|
|
130
|
+
- Tool results, pages included, live inside one call of `askGemini`. They are not sent again with
|
|
131
|
+
the next question.
|
|
132
|
+
|
|
133
|
+
### With an explorer model
|
|
134
|
+
|
|
135
|
+
One model does all of the above unless the endpoint names an explorer
|
|
136
|
+
([configuration](configuration.md#an-explorer-model)). Then the loop is split in two:
|
|
137
|
+
|
|
138
|
+
- **The requests with tools go to the explorer.** It gets the same conversation, the same tool
|
|
139
|
+
guide and a line that says what its part is: gather what the answer needs, then reply `DONE`.
|
|
140
|
+
Its turns go back to it unchanged, thought signatures included. Reading a whole file in parts is
|
|
141
|
+
its work too.
|
|
142
|
+
- **The request without tools goes to the answering model**, and with an explorer it is always
|
|
143
|
+
made. It holds the conversation, the explorer's function calls, and the function responses, pages
|
|
144
|
+
included. It does not hold the explorer's thoughts, its thought signatures, or anything it
|
|
145
|
+
wrote: the answer is written from what the files say.
|
|
146
|
+
- **That request ends with a user message.** A Gemini 3 model refuses a request that ends with
|
|
147
|
+
the result of a function call it did not sign (HTTP 400, "Function call is missing a
|
|
148
|
+
thought_signature"), and a signature belongs to the model that made the call. With a user message
|
|
149
|
+
after the results, the calls belong to an earlier turn, and the request is accepted without
|
|
150
|
+
signatures. The message is the "answer now" one from above.
|
|
151
|
+
- An explorer that calls no tool leaves nothing to answer from but the conversation, so the
|
|
152
|
+
message then says that instead (`FINAL_ANSWER_WITHOUT_TOOLS`).
|
|
87
153
|
|
|
88
154
|
## Live results
|
|
89
155
|
|
|
@@ -94,3 +160,6 @@ Jobs needing more than `maxMapChunks` parts are refused, with advice to narrow t
|
|
|
94
160
|
| 5 MB, 60,000-line log (1.27M tokens by the 0.1.0 estimate, which undercounted logs) | Correct root cause, failover time, and affected services, citing the right lines (checked with grep). About 60 s, 11 tool calls, about 15K prompt tokens per turn. |
|
|
95
161
|
| 467 KB novel | Sent whole. Token estimate 116,840; Gemini billed 116,842. |
|
|
96
162
|
| Map-reduce on the novel, 40K-token parts | 4 parts, 1 relevant. Correct answer citing L2036. 32 s. |
|
|
163
|
+
|
|
164
|
+
The checks of `view_pages`, on `gemini-3.5-flash-lite`, are in
|
|
165
|
+
[Pictures in PDFs](configuration.md#live-results).
|
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)
|
|
52
|
-
your process. Keep
|
|
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.
|
|
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,
|
|
3
|
+
"version": "0.3.5",
|
|
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 {
|
|
2
|
-
import
|
|
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
|
-
|
|
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
|
|
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 =
|
|
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
|
-
|
|
204
|
+
texts.push(text);
|
|
205
|
+
geometry.push({ view: page.view, transform, tables: found });
|
|
189
206
|
page.cleanup();
|
|
190
207
|
}
|
|
191
208
|
if (!hasText) {
|
|
192
|
-
|
|
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:
|
|
237
|
+
input: ExtractInput,
|
|
212
238
|
extractors: Partial<Record<DocumentFormat, Extractor>> = {},
|
|
213
239
|
): Promise<ExtractedText> {
|
|
214
240
|
const extractor = extractors[input.format] ?? defaultExtractors[input.format];
|