llm-large-files 0.4.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1400 -338
- package/README.md +217 -49
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +117 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +542 -0
- package/dist/anthropic/adapter.js.map +1 -0
- package/dist/anthropic/index.d.ts +3 -0
- package/dist/anthropic/index.d.ts.map +1 -0
- package/dist/anthropic/index.js +2 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/ask.d.ts +200 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +1402 -0
- package/dist/ask.js.map +1 -0
- package/dist/budget.d.ts +23 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +64 -0
- package/dist/budget.js.map +1 -0
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +42 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +138 -0
- package/dist/evidence.js.map +1 -0
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +59 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +226 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +53 -77
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +42 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +16 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +46 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +18 -21
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +49 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +6 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +4 -3
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -2
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -38
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +136 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +401 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +96 -8
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +414 -96
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +37 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +255 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +278 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +222 -0
- package/dist/model.js.map +1 -0
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +109 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +567 -0
- package/dist/openai/adapter.js.map +1 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +2 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/output-limit.d.ts +42 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +121 -0
- package/dist/output-limit.js.map +1 -0
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +76 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +141 -0
- package/dist/retry.js.map +1 -0
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +36 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +153 -0
- package/dist/sse.js.map +1 -0
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +72 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +341 -60
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +128 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +58 -184
- package/docs/configuration.md +34 -490
- package/docs/getting-started.md +412 -177
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1022 -138
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +902 -90
- package/docs/troubleshooting.md +1390 -0
- package/package.json +22 -4
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +611 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +1560 -0
- package/src/budget.ts +71 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +165 -0
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +271 -0
- package/src/gemini/chat.ts +87 -355
- package/src/gemini/errors.ts +48 -0
- package/src/gemini/generate.ts +67 -94
- package/src/gemini/index.ts +6 -4
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +434 -0
- package/src/index.ts +55 -4
- package/src/library.ts +497 -97
- package/src/map-reduce.ts +266 -59
- package/src/model.ts +433 -0
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +613 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +135 -0
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +176 -0
- package/src/search.ts +63 -10
- package/src/sse.ts +159 -0
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +338 -62
- package/src/types.ts +129 -5
- package/src/zip-directory.ts +136 -0
package/README.md
CHANGED
|
@@ -12,70 +12,190 @@ and 1M tokens of context. This package bridges the gap:
|
|
|
12
12
|
- **Pictures in a PDF** are not in its text. The model can **look at the real pages** when it
|
|
13
13
|
needs to: a chart, a photo, a scan.
|
|
14
14
|
|
|
15
|
-
It's a small library, not a framework: no model SDK, no server, and no UI are required.
|
|
16
|
-
|
|
15
|
+
It's a small library, not a framework: no model SDK, no server, and no UI are required. One tool
|
|
16
|
+
loop, `askWithFiles`, works with any model through an adapter. Adapters for **Gemini and Vertex
|
|
17
|
+
AI**, **any OpenAI-compatible endpoint** and **Claude** are included, and so are Node HTTP handlers.
|
|
17
18
|
|
|
18
19
|
```bash
|
|
19
20
|
npm install llm-large-files
|
|
20
21
|
```
|
|
21
22
|
|
|
22
|
-
## Quickstart
|
|
23
|
+
## Quickstart
|
|
24
|
+
|
|
25
|
+
With Gemini on Vertex AI, and an access token from Application Default Credentials
|
|
26
|
+
(`npm install google-auth-library`; on your own machine, `gcloud auth application-default login`):
|
|
23
27
|
|
|
24
28
|
```ts
|
|
29
|
+
import { readFile } from "node:fs/promises";
|
|
30
|
+
import { GoogleAuth } from "google-auth-library";
|
|
25
31
|
import { createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
26
|
-
import { askGemini,
|
|
32
|
+
import { askGemini, vertexAi } from "llm-large-files/gemini";
|
|
27
33
|
|
|
28
34
|
const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
|
|
29
35
|
|
|
30
36
|
// When a user uploads a file:
|
|
31
|
-
const doc = await files.ingest({ name: "app.log", bytes:
|
|
37
|
+
const doc = await files.ingest({ name: "app.log", bytes: await readFile("./app.log") });
|
|
32
38
|
|
|
33
39
|
// When they ask about it:
|
|
34
|
-
const
|
|
40
|
+
const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
|
|
41
|
+
const endpoint = vertexAi({
|
|
42
|
+
project: process.env.GOOGLE_CLOUD_PROJECT!,
|
|
43
|
+
model: "gemini-3.8-flash",
|
|
44
|
+
accessToken: async () => (await auth.getAccessToken())!, // asked for on each request
|
|
45
|
+
});
|
|
46
|
+
const result = await askGemini({
|
|
35
47
|
files,
|
|
36
|
-
endpoint
|
|
48
|
+
endpoint,
|
|
37
49
|
documentIds: [doc.id],
|
|
38
50
|
messages: [{ role: "user", text: "What caused the outage, and when? Cite lines." }],
|
|
39
|
-
onText: (delta) => process.stdout.write(delta), // optional
|
|
51
|
+
onText: (delta) => process.stdout.write(delta), // optional: the answer as it streams
|
|
40
52
|
});
|
|
41
53
|
```
|
|
42
54
|
|
|
43
|
-
`steps` lists
|
|
44
|
-
`Search app.log (exact) for “failover” —
|
|
45
|
-
|
|
55
|
+
`result.steps` lists the tool calls in order, such as
|
|
56
|
+
`Search app.log (exact) for “failover” — 12 matching lines`, with the loop's own notices among
|
|
57
|
+
them (`Older tool results were shortened to make room in the request`). Show it under the answer so
|
|
58
|
+
users can see where the answer came from, as plain text: the steps quote what the model sent.
|
|
59
|
+
|
|
60
|
+
Using the **Gemini API** with a key, or an **enterprise gateway**? Swap the endpoint:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import { geminiApi, type GeminiEndpoint } from "llm-large-files/gemini";
|
|
64
|
+
|
|
65
|
+
const withKey = geminiApi({ apiKey: process.env.GEMINI_API_KEY!, model: "gemini-3.8-flash" });
|
|
66
|
+
|
|
67
|
+
// Your own proxy of Generate Content. Its headers are sent exactly as given.
|
|
68
|
+
const viaGateway: GeminiEndpoint = {
|
|
69
|
+
url: "https://llm-gateway.example.com/v1/gemini:generateContent",
|
|
70
|
+
streamUrl: "https://llm-gateway.example.com/v1/gemini:streamGenerateContent?alt=sse", // without it, no streaming
|
|
71
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.GATEWAY_KEY}` },
|
|
72
|
+
};
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Any model
|
|
46
76
|
|
|
47
|
-
|
|
77
|
+
`askGemini` is `askWithFiles` with a Gemini model. With another provider, name the model yourself:
|
|
48
78
|
|
|
49
79
|
```ts
|
|
50
|
-
import {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
80
|
+
import { askWithFiles } from "llm-large-files";
|
|
81
|
+
import { openAiCompatible } from "llm-large-files/openai";
|
|
82
|
+
import { anthropic } from "llm-large-files/anthropic";
|
|
83
|
+
|
|
84
|
+
// OpenAI, Azure OpenAI, DeepSeek, LiteLLM, vLLM, Ollama, OpenRouter: anything that speaks Chat Completions.
|
|
85
|
+
const deepseek = openAiCompatible({ baseUrl: "https://api.deepseek.com/v1", apiKey: process.env.DEEPSEEK_API_KEY!, model: "deepseek-v4-pro" });
|
|
86
|
+
// Claude. `fallbacks` lets another model answer when a safety classifier declines the request.
|
|
87
|
+
const claude = anthropic({ apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-opus-5-5", fallbacks: "default" });
|
|
88
|
+
|
|
89
|
+
const withClaude = await askWithFiles({
|
|
90
|
+
files, // `files` and `doc` are those of the quickstart
|
|
91
|
+
model: claude, // writes the answer
|
|
92
|
+
explorer: deepseek, // optional: a second model, of any provider, that searches and reads
|
|
93
|
+
documentIds: [doc.id],
|
|
94
|
+
messages: [{ role: "user", text: "What caused the outage, and when? Cite lines." }],
|
|
95
|
+
onText: (delta) => process.stdout.write(delta),
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
withClaude.answered; // false when the last reply had no text (a blocked prompt, a reply cut off before any text, a tool call that could not be read): show your own message
|
|
99
|
+
withClaude.usage; // { requests: 5, inputTokens: 32662, cachedInputTokens: 6086, outputTokens: 750, thoughtTokens: 0, byModel: { … } }
|
|
100
|
+
withClaude.evidence; // [{ tool: "read_document", documentId, document: "app.log", lines: [[34100, 34110]] }, …]
|
|
101
|
+
withClaude.toolTurns; // pass these back in `messages`, between this question and its answer: a follow-up then needs no new search
|
|
54
102
|
```
|
|
55
103
|
|
|
104
|
+
How to keep a chat's history, tool turns included, across requests and servers:
|
|
105
|
+
[Conversations](docs/guides/conversations.md).
|
|
106
|
+
|
|
107
|
+
Every model gets the same loop. A failed request is sent again when another try can help (a lost
|
|
108
|
+
connection, HTTP 408, 409, 429 or 5xx), never for a quota that ran out or once text was shown. With
|
|
109
|
+
the built-in adapters, a model silent for 10 minutes before its reply (`firstByteTimeoutMs`) or 5
|
|
110
|
+
minutes inside it (`idleTimeoutMs`) is cut off and asked once more. A request the provider refuses
|
|
111
|
+
as too large is made smaller, or the files are planned again for a window a little smaller than the
|
|
112
|
+
one it names. An empty first reply, an unreadable tool call, or an answer that comes back without
|
|
113
|
+
text is asked for again, a repeated call gets a pointer to the result already shown, and by default
|
|
114
|
+
each file is read whole at most once a question.
|
|
115
|
+
|
|
116
|
+
A question that fails throws `DocumentsNotFoundError` for a file that expired, was deleted, or
|
|
117
|
+
belongs to another `owner`, `DocumentStoreError` when the store cannot be read, or a
|
|
118
|
+
`ModelRequestError` whose `kind` (`"rate_limit"`, `"quota"`, `"timeout"`, `"context_overflow"`, …)
|
|
119
|
+
tells you what to show the user. `partialResultOf(error)` gives what it found and paid for:
|
|
120
|
+
[Errors and reliability](docs/guides/errors-and-reliability.md).
|
|
121
|
+
|
|
122
|
+
A model that has no adapter needs one object with an `id`, its `capabilities` (at least `toolFiles`
|
|
123
|
+
and `pageTokens`) and a `send` method, plus `generateText` to read whole files in parts:
|
|
124
|
+
[your own adapter](docs/guides/own-adapter-and-loop.md).
|
|
125
|
+
|
|
56
126
|
## Add it to a web app
|
|
57
127
|
|
|
58
128
|
```ts
|
|
59
129
|
import express from "express";
|
|
60
130
|
import { createDocumentHandlers } from "llm-large-files/node";
|
|
61
131
|
|
|
62
|
-
const
|
|
63
|
-
|
|
132
|
+
const app = express();
|
|
133
|
+
// `files` is the quickstart's. getOwner names the signed-in user (here, set on req.user by your
|
|
134
|
+
// auth middleware): each upload is then theirs alone.
|
|
135
|
+
const documents = createDocumentHandlers(files, {
|
|
136
|
+
getOwner: (req) => (req as typeof req & { user?: { id: string } }).user?.id,
|
|
137
|
+
});
|
|
138
|
+
app.post("/api/documents", documents.upload); // mount before express.json(): the body is the raw file
|
|
139
|
+
app.get("/api/documents/:id", (req, res) => documents.get(req, res, req.params.id));
|
|
64
140
|
app.delete("/api/documents/:id", (req, res) => documents.remove(req, res, req.params.id));
|
|
65
141
|
```
|
|
66
142
|
|
|
67
|
-
The browser uploads the raw file:
|
|
143
|
+
The browser uploads the raw file (`file` comes from an `<input type="file">`):
|
|
68
144
|
|
|
69
145
|
```ts
|
|
70
|
-
await fetch("/api/documents", {
|
|
146
|
+
const response = await fetch("/api/documents", {
|
|
71
147
|
method: "POST",
|
|
72
148
|
headers: { "Content-Type": "application/octet-stream", "X-File-Name": encodeURIComponent(file.name) },
|
|
73
149
|
body: file,
|
|
74
|
-
});
|
|
150
|
+
});
|
|
151
|
+
const summary = await response.json(); // 201: { id, name, format, lines, estimatedTokens, expiresAt, … }; otherwise { error }
|
|
75
152
|
```
|
|
76
153
|
|
|
77
|
-
|
|
78
|
-
|
|
154
|
+
When the user asks, stream the question to the page with `askStream` (new in 0.7.0): typed events
|
|
155
|
+
in order, from `run.start` through each tool call, its progress and the text as it is written, to
|
|
156
|
+
`run.finish` or `run.error`. Errors in events are told in words for users, and no text of the
|
|
157
|
+
documents is in them:
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
import { askStream } from "llm-large-files";
|
|
161
|
+
import { writeSseEvents } from "llm-large-files/node";
|
|
162
|
+
|
|
163
|
+
app.post("/api/chat", express.json(), async (req, res) => {
|
|
164
|
+
const stream = askStream({
|
|
165
|
+
files, model: claude, // `claude` is the adapter of "Any model"
|
|
166
|
+
owner: (req as typeof req & { user?: { id: string } }).user?.id,
|
|
167
|
+
documentIds: [String(req.body.documentId)],
|
|
168
|
+
messages: [{ role: "user", text: String(req.body.question) }],
|
|
169
|
+
});
|
|
170
|
+
await writeSseEvents(res, stream); // one SSE message per event; stops the question if the page leaves
|
|
171
|
+
});
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
Pass the upload's `id` in `documentIds` and the same user as `owner`: a document
|
|
175
|
+
that has an owner is missing for anyone else. This `getOwner` returns `undefined` for an anonymous
|
|
176
|
+
upload. Never return an empty string: it would be one owner shared by every caller without a user,
|
|
177
|
+
and the upload is answered 500. Reading the events in the browser, the upload's own progress, and
|
|
178
|
+
cancelling are in the [web app guide](docs/guides/web-app.md); every event is in
|
|
179
|
+
[Events](docs/reference/events.md). There's also a
|
|
180
|
+
[one-file demo server](https://github.com/renanbazinin/llm-large-files/blob/main/examples/server.ts) and a [command-line script](https://github.com/renanbazinin/llm-large-files/blob/main/examples/ask-cli.ts): from a
|
|
181
|
+
clone of this repository, run `npm install` and `npm run build`, then run them with Node 22.18 or a
|
|
182
|
+
later 22.x, or Node 23.6 or later.
|
|
183
|
+
|
|
184
|
+
**Uploads you do not trust.** These handlers read each upload in your server's process. Ingest
|
|
185
|
+
limits the text, the pages and the time of one file, refuses the zip bombs and the PDFs built to
|
|
186
|
+
hold a server that its checks recognize, and pauses for other requests between pages and slices of
|
|
187
|
+
its work. It does not refuse every file built to hurt a server. While a file is read, it takes
|
|
188
|
+
memory from your server's heap. Some steps run in one block, and no other request is answered
|
|
189
|
+
meanwhile. pdf.js reads one page of a PDF in one block: up to about 1.5 s for a page of a small
|
|
190
|
+
file that passes the page check, longer in a large file. `@cantoo/pdf-lib` reads one object of a
|
|
191
|
+
PDF in one block, about 0.1 to 0.35 s for each MB of it. Neither it nor pdf.js checks the memory
|
|
192
|
+
an object takes before building it: a crafted PDF of 732 bytes, whose object stream unpacks to
|
|
193
|
+
4 MB of empty dictionaries, ran a heap of 512 MB out of memory at ingest. What a stream unpacks to
|
|
194
|
+
is outside the heap: one of 1.6 KB took 1.6 GB of memory with 20 MB of heap. If your users can
|
|
195
|
+
upload files you do not trust, ingest them in a child process with its own heap limit, memory
|
|
196
|
+
limit and timer, as [Deployment](docs/guides/deployment.md#uploads-and-ingest) shows, and do not
|
|
197
|
+
offer `view_pages` on their documents. What is refused, and what still holds the server:
|
|
198
|
+
[Security](docs/security.md#uploads).
|
|
79
199
|
|
|
80
200
|
## Pictures, charts and scans in PDFs
|
|
81
201
|
|
|
@@ -83,21 +203,28 @@ A large PDF goes to the model as text, and text cannot show a chart. Keep the up
|
|
|
83
203
|
the model gets a tool, `view_pages`, that hands it the pages it asks for as a small PDF:
|
|
84
204
|
|
|
85
205
|
```bash
|
|
86
|
-
npm install @cantoo/pdf-lib
|
|
206
|
+
npm install unpdf @cantoo/pdf-lib # Node 24; for Node 20 and 22, see Requirements
|
|
87
207
|
```
|
|
88
208
|
|
|
89
209
|
```ts
|
|
210
|
+
// In place of the quickstart's files:
|
|
90
211
|
const files = createLargeFiles({
|
|
91
212
|
store: new FileDocumentStore("./data/large-files"),
|
|
92
|
-
keepOriginals: ["pdf"],
|
|
213
|
+
keepOriginals: ["pdf"], // off by default: a kept file takes disk space until it expires and is swept
|
|
93
214
|
});
|
|
215
|
+
setInterval(() => files.sweep().catch(console.error), 60 * 60 * 1000).unref(); // removes expired documents and their files
|
|
94
216
|
// askGemini needs no change. A step then reads: Look at report.pdf pages 12-14
|
|
95
217
|
```
|
|
96
218
|
|
|
219
|
+
`unpdf` reads the text of a PDF, and `@cantoo/pdf-lib` cuts its pages. With `askWithFiles`,
|
|
220
|
+
`view_pages` is offered only when every model of the question can be sent a file: `gemini()` and
|
|
221
|
+
`anthropic()` can by default, `openAiCompatible()` only with `pdfInput: true`. So the question
|
|
222
|
+
above, with DeepSeek exploring, is not offered `view_pages` at all.
|
|
223
|
+
|
|
97
224
|
Asked which bar of a chart is tallest, `gemini-3.5-flash-lite` said from the text that it could
|
|
98
225
|
not see the chart; with `view_pages` it looked at the page and answered correctly. It did not look
|
|
99
|
-
at a page for any of ten questions that the text answers.
|
|
100
|
-
|
|
226
|
+
at a page for any of ten questions that the text answers. On Gemini a page costs about 530 tokens;
|
|
227
|
+
`anthropic()` counts 3,500 for Claude by default. Scans, tables, limits: [PDFs](docs/guides/pdfs.md).
|
|
101
228
|
|
|
102
229
|
## One model to explore, another to answer
|
|
103
230
|
|
|
@@ -106,10 +233,12 @@ default. That model does both halves of the work on a large file. It explores th
|
|
|
106
233
|
reads, looks at pages), and then it answers. You can name a second model for the first half:
|
|
107
234
|
|
|
108
235
|
```ts
|
|
109
|
-
|
|
110
|
-
|
|
236
|
+
// In place of the quickstart's endpoint:
|
|
237
|
+
const endpoint = vertexAi({
|
|
238
|
+
project: process.env.GOOGLE_CLOUD_PROJECT!,
|
|
111
239
|
model: "gemini-3.8-flash", // writes the answer
|
|
112
240
|
explorerModel: process.env.GEMINI_EXPLORER_MODEL, // optional: searches and reads
|
|
241
|
+
accessToken: async () => (await auth.getAccessToken())!, // `auth` is the quickstart's
|
|
113
242
|
});
|
|
114
243
|
```
|
|
115
244
|
|
|
@@ -117,48 +246,87 @@ Left out or empty, nothing changes: one model does both. With an explorer, the m
|
|
|
117
246
|
search through a large file go to that model, which can be a cheaper or faster one, and `model`
|
|
118
247
|
gets what the tools returned and writes the answer in one request. In eleven live checks with
|
|
119
248
|
`gemini-3.5-flash-lite` exploring, the other model answered every one correctly from what it found.
|
|
120
|
-
What each model gets, and what it costs: [An explorer model](docs/
|
|
249
|
+
What each model gets, and what it costs: [An explorer model](docs/guides/explorer-model.md).
|
|
121
250
|
|
|
122
251
|
## What it handles
|
|
123
252
|
|
|
124
253
|
| | |
|
|
125
254
|
|---|---|
|
|
126
|
-
| **Formats** | Text, Markdown, logs (UTF-8 and UTF-16), JSON/JSONL, CSV/TSV, DOCX, PPTX, PDF (text layer, with tables rebuilt so empty cells stay empty; pages with a picture are marked, and the model can look at the pages themselves; scans of up to 30 pages) |
|
|
255
|
+
| **Formats** | Text, Markdown, logs (UTF-8 and UTF-16, and Hebrew, Arabic, Cyrillic, Japanese and Western European text in its older encoding), JSON/JSONL, CSV/TSV, DOCX, PPTX, PDF (text layer, with tables rebuilt so empty cells stay empty; pages with a picture are marked, and the model can look at the pages themselves; scans of up to 30 pages when PDFs are kept) |
|
|
127
256
|
| **Logs** | Detected automatically; the card shows level counts, the time range, and the most frequent errors grouped by shape (`timeout after <n>ms to <ip>`) |
|
|
128
257
|
| **Books and documents** | An outline of headings with line numbers, including Markdown, "Chapter 12", numbered sections, and Hebrew chapter titles |
|
|
129
|
-
| **Limits** | One budget covers tokens *and* request bytes, so files fit both your context window and your connector's payload limit |
|
|
258
|
+
| **Limits** | One budget covers tokens *and* request bytes, so files fit both your context window and your connector's payload limit. It assumes 1M tokens and 10 MB: set `budget.contextTokens` for your model's window (an adapter's `contextTokens` can only make it smaller) |
|
|
259
|
+
| **Reliability** | Retries, waits on a silent model, recovery from a request too large, error kinds: see [Errors and reliability](docs/guides/errors-and-reliability.md) |
|
|
260
|
+
| **Models** | Gemini and Vertex AI, any OpenAI-compatible endpoint, Claude, or an adapter of your own. Two models of different providers can share a question |
|
|
261
|
+
| **Cost** | Usage summed over every request of a question, for each model, with ceilings on whole-file reads, requests and input tokens |
|
|
130
262
|
| **Privacy** | Documents can belong to an `owner`; other users can't plan, read, or delete them |
|
|
263
|
+
| **Hostile uploads** | Limits on the text, pages and time of one file; zip bombs and PDFs built to exhaust a server are refused when the checks recognize them; ingest pauses for other requests between pages and slices. Not every hostile file is refused, parsing shares your server's heap, and some steps hold the server for a while: ingest untrusted uploads in a process of their own ([Security](docs/security.md#uploads)) |
|
|
131
264
|
| **Storage** | In memory, on disk with expiry, or your own store (Redis, S3, a database) |
|
|
132
265
|
|
|
133
266
|
## Live results
|
|
134
267
|
|
|
135
|
-
With `gemini-3.8-flash` on the Gemini API
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
| 5 MB log, about 1.27M tokens (over the 1M limit) | "What caused the outage?" | Correct root cause, citing the right lines, in about 60 s over 11 tool calls |
|
|
140
|
-
| 467 KB novel, about 117K tokens | "Where was the ledger hidden?" | Sent whole; correct. Estimated 116,840 tokens; Gemini billed 116,842 |
|
|
141
|
-
| Same novel, map-reduce | "Read all of it…" | 4 parts read in parallel; correct, cited answer in 32 s |
|
|
142
|
-
| PDF with a chart and photos (`gemini-3.5-flash-lite`) | "Which bar is tallest, and what number is on the sign?" | Looked at 2 pages unasked; all five facts right, in 3 s. From the text alone: "cannot see the chart" |
|
|
268
|
+
With `gemini-3.8-flash` on the Gemini API, a 5 MB log of about 1.27M tokens, over the 1M window,
|
|
269
|
+
got the right root cause of an outage, citing the right lines, in about 60 s over 11 tool calls.
|
|
270
|
+
Every live result with its date, model and setup, and what has not been run live, such as the
|
|
271
|
+
Claude adapter: [Measurements](docs/measurements.md).
|
|
143
272
|
|
|
144
273
|
## Documentation
|
|
145
274
|
|
|
146
|
-
- [
|
|
147
|
-
- [
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
275
|
+
- [Documentation index](docs/README.md): where to start, which entry point to use, a glossary, and every page in one line.
|
|
276
|
+
- [Getting started](docs/getting-started.md): install, a quickstart that runs, and the integration in short steps.
|
|
277
|
+
|
|
278
|
+
Guides, one task each:
|
|
279
|
+
|
|
280
|
+
- [Gemini and Vertex AI](docs/guides/vertex-and-gemini.md): endpoints, access tokens, thinking, whole-file reads, pages, gateways, Vertex quotas and errors.
|
|
281
|
+
- [OpenAI-compatible endpoints](docs/guides/openai-compatible.md): OpenAI, Azure OpenAI, DeepSeek, OpenRouter, vLLM, Ollama, LiteLLM, llama.cpp.
|
|
282
|
+
- [Claude](docs/guides/anthropic.md): setup, thinking, streaming, conversations that may only grow, gateways.
|
|
283
|
+
- [An explorer model](docs/guides/explorer-model.md): a cheaper model that explores the files while another answers.
|
|
284
|
+
- [Web app](docs/guides/web-app.md): uploads, answers and progress streamed over Server-Sent Events, cancelling.
|
|
285
|
+
- [Conversations](docs/guides/conversations.md): the history you keep, tool turns included, across requests and servers.
|
|
286
|
+
- [Storage](docs/guides/storage.md): the store contract, owners, a layout per user and per chat session, retention.
|
|
287
|
+
- [Deployment](docs/guides/deployment.md): several servers, memory, sweeps, proxies and timeouts for streams, upgrades.
|
|
288
|
+
- [Errors and reliability](docs/guides/errors-and-reliability.md): every error and what to show the user, retries, waits, deadlines.
|
|
289
|
+
- [Costs and limits](docs/guides/costs-and-limits.md): the limits of a question, the budget per model, usage per user or session.
|
|
290
|
+
- [PDFs](docs/guides/pdfs.md): formats and optional packages, tables, pictures, `view_pages`, scans, extractors and OCR.
|
|
291
|
+
- [Your own adapter or loop](docs/guides/own-adapter-and-loop.md): a model without an adapter, or a tool loop of your own.
|
|
292
|
+
- [Testing](docs/guides/testing.md): testing your integration without a real model.
|
|
293
|
+
|
|
294
|
+
Reference, one page per module:
|
|
295
|
+
|
|
296
|
+
- [`llm-large-files`: the library and its documents](docs/reference/library.md): `createLargeFiles`, stores, budget, extractors.
|
|
297
|
+
- [`llm-large-files`: the tool loop](docs/reference/ask.md): `askWithFiles`, its options and result, the adapter contract.
|
|
298
|
+
- [`llm-large-files`: errors, retries, streams](docs/reference/errors-and-retries.md): `ModelRequestError` and its kinds, `withRetry`, `parseSseJson`.
|
|
299
|
+
- [`llm-large-files`: the tools](docs/reference/tools.md): every tool the model sees, its arguments, results and limits.
|
|
300
|
+
- [`llm-large-files`: events](docs/reference/events.md): `askStream`, the events of a question and of an ingest, `eventStream`.
|
|
301
|
+
- [`llm-large-files/gemini`](docs/reference/gemini.md): `askGemini`, `gemini()`, `geminiApi()`, `vertexAi()`.
|
|
302
|
+
- [`llm-large-files/openai`](docs/reference/openai.md): `openAiCompatible()` and its options.
|
|
303
|
+
- [`llm-large-files/anthropic`](docs/reference/anthropic.md): `anthropic()` and its options.
|
|
304
|
+
- [`llm-large-files/node`](docs/reference/node.md): `createDocumentHandlers`, its routes and responses.
|
|
305
|
+
|
|
306
|
+
[Changelog](CHANGELOG.md): what each version changed, and what to change in your code when you upgrade.
|
|
307
|
+
|
|
308
|
+
Also: [How it works](docs/how-it-works.md), [Security](docs/security.md),
|
|
309
|
+
[Troubleshooting](docs/troubleshooting.md) and [Measurements](docs/measurements.md). For
|
|
310
|
+
maintainers: [Contributing](https://github.com/renanbazinin/llm-large-files/blob/main/CONTRIBUTING.md) and [Publishing](docs/publishing.md).
|
|
151
311
|
|
|
152
312
|
## Requirements
|
|
153
313
|
|
|
154
|
-
Node.js 20.19 or newer. The package is ESM; CommonJS
|
|
155
|
-
For DOCX/PPTX install `jszip`, for PDF install `unpdf`, and to mark and show the pages of a
|
|
156
|
-
install `@cantoo/pdf-lib`. All
|
|
314
|
+
Node.js 20.19 or newer. The package is ESM; CommonJS code can `require()` it on Node 20.19+ and
|
|
315
|
+
22.12+. For DOCX/PPTX install `jszip`, for PDF install `unpdf`, and to mark and show the pages of a
|
|
316
|
+
PDF, and refuse a page built to hold the server before it is read, install `@cantoo/pdf-lib`. All
|
|
317
|
+
three are optional:
|
|
157
318
|
|
|
158
319
|
```bash
|
|
159
|
-
npm install jszip unpdf @cantoo/pdf-lib
|
|
320
|
+
npm install jszip unpdf @cantoo/pdf-lib # Node 24 and later
|
|
321
|
+
npm install jszip unpdf@1 @cantoo/pdf-lib # Node 22
|
|
322
|
+
npm install jszip unpdf@1.7.0 @cantoo/pdf-lib # Node 20
|
|
160
323
|
```
|
|
161
324
|
|
|
325
|
+
On Node 24 and later, `npm install unpdf` installs unpdf 2, which asks for Node 24. On Node 20,
|
|
326
|
+
unpdf 1.9 and later cannot load pdf.js, and on Node 20 and 22 the pdf.js of unpdf 1.5.0 to 1.6.0
|
|
327
|
+
would stop the whole process. Such an unpdf is refused at the first PDF, with a message that says
|
|
328
|
+
what to install.
|
|
329
|
+
|
|
162
330
|
## License
|
|
163
331
|
|
|
164
332
|
[MIT](LICENSE)
|
package/dist/analyze.d.ts
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
|
+
import type { TimeSlicer } from "./pause.js";
|
|
1
2
|
import type { DocumentFormat, LogProfile, OutlineEntry } from "./types.js";
|
|
2
3
|
/** Treats text as a log when most early lines start with a timestamp or a level. */
|
|
3
4
|
export declare function looksLikeLog(lines: string[]): boolean;
|
|
4
5
|
/** Headings with line numbers: Markdown, slide/page markers, and common book and report patterns. */
|
|
5
6
|
export declare function buildOutline(lines: string[], format: DocumentFormat): OutlineEntry[];
|
|
7
|
+
/** `buildOutline`, the same result, with pauses for other requests while a large file is read. */
|
|
8
|
+
export declare function buildOutlineInSlices(lines: string[], format: DocumentFormat, slicer: TimeSlicer): Promise<OutlineEntry[]>;
|
|
6
9
|
/** Replaces the variable parts of a log message so repeated failures group together. */
|
|
7
10
|
export declare function logTemplate(line: string): string;
|
|
8
11
|
export declare function buildLogProfile(lines: string[]): LogProfile;
|
|
12
|
+
/** `buildLogProfile`, the same result, with pauses for other requests while a large log is read. */
|
|
13
|
+
export declare function buildLogProfileInSlices(lines: string[], slicer: TimeSlicer): Promise<LogProfile>;
|
|
9
14
|
//# sourceMappingURL=analyze.d.ts.map
|
package/dist/analyze.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analyze.d.ts","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAY,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AASrF,oFAAoF;AACpF,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,
|
|
1
|
+
{"version":3,"file":"analyze.d.ts","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,OAAO,KAAK,EAAE,cAAc,EAAY,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AASrF,oFAAoF;AACpF,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAMrD;AAED,qGAAqG;AACrG,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,cAAc,GAAG,YAAY,EAAE,CAQpF;AAED,kGAAkG;AAClG,wBAAsB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAS/H;AAsCD,wFAAwF;AACxF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAYhD;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,UAAU,CAI3D;AAED,oGAAoG;AACpG,wBAAsB,uBAAuB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAOtG"}
|
package/dist/analyze.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { sliceWhole } from "./text.js";
|
|
1
2
|
const MAX_OUTLINE_ENTRIES = 400;
|
|
2
3
|
const MAX_TEMPLATES = 50_000;
|
|
3
4
|
const TIMESTAMP = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?/;
|
|
@@ -6,7 +7,10 @@ const LEVEL = /\b(FATAL|CRITICAL|ERROR|ERR|WARN|WARNING|INFO|DEBUG|TRACE)\b/;
|
|
|
6
7
|
const LEVEL_NAMES = { ERR: "ERROR", WARNING: "WARN", CRITICAL: "FATAL" };
|
|
7
8
|
/** Treats text as a log when most early lines start with a timestamp or a level. */
|
|
8
9
|
export function looksLikeLog(lines) {
|
|
9
|
-
const sample =
|
|
10
|
+
const sample = [];
|
|
11
|
+
for (let index = 0; index < lines.length && sample.length < 200; index++)
|
|
12
|
+
if (lines[index].trim())
|
|
13
|
+
sample.push(lines[index]);
|
|
10
14
|
if (sample.length < 5)
|
|
11
15
|
return false;
|
|
12
16
|
const hits = sample.filter((line) => LINE_START_TIMESTAMP.test(line.trim()) || /^\[?(FATAL|ERROR|WARN|WARNING|INFO|DEBUG|TRACE)\b/.test(line.trim())).length;
|
|
@@ -18,30 +22,53 @@ export function buildOutline(lines, format) {
|
|
|
18
22
|
return [];
|
|
19
23
|
const entries = [];
|
|
20
24
|
for (let index = 0; index < lines.length; index++) {
|
|
21
|
-
const
|
|
22
|
-
if (
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
entry = { line: index + 1, level: (line.split(" ")[0].match(/\./g)?.length ?? 0) + 2, title: line };
|
|
35
|
-
}
|
|
36
|
-
else if (previousBlank && line.length >= 4 && line.length <= 60 && /\p{Lu}/u.test(line) && line === line.toUpperCase() && /\p{L}{3}/u.test(line)) {
|
|
37
|
-
entry = { line: index + 1, level: 2, title: line };
|
|
38
|
-
}
|
|
25
|
+
const entry = outlineEntry(lines, index);
|
|
26
|
+
if (entry)
|
|
27
|
+
entries.push(entry);
|
|
28
|
+
}
|
|
29
|
+
return pickOutline(entries);
|
|
30
|
+
}
|
|
31
|
+
/** `buildOutline`, the same result, with pauses for other requests while a large file is read. */
|
|
32
|
+
export async function buildOutlineInSlices(lines, format, slicer) {
|
|
33
|
+
if (format === "log" || format === "json" || format === "csv")
|
|
34
|
+
return [];
|
|
35
|
+
const entries = [];
|
|
36
|
+
for (let index = 0; index < lines.length; index++) {
|
|
37
|
+
const entry = outlineEntry(lines, index);
|
|
39
38
|
if (entry)
|
|
40
39
|
entries.push(entry);
|
|
40
|
+
if ((index & 4095) === 4095)
|
|
41
|
+
await slicer.maybePause();
|
|
42
|
+
}
|
|
43
|
+
return pickOutline(entries);
|
|
44
|
+
}
|
|
45
|
+
/** The heading on line `index` (0-based), if it is one. */
|
|
46
|
+
function outlineEntry(lines, index) {
|
|
47
|
+
const line = (lines[index] ?? "").trim();
|
|
48
|
+
if (!line || line.length > 120)
|
|
49
|
+
return undefined;
|
|
50
|
+
const previousBlank = index === 0 || !(lines[index - 1] ?? "").trim();
|
|
51
|
+
const markdown = /^(#{1,6})\s+(.+)$/.exec(line);
|
|
52
|
+
if (markdown)
|
|
53
|
+
return { line: index + 1, level: markdown[1].length, title: markdown[2].trim() };
|
|
54
|
+
// A lookahead, not \b: JavaScript's \b does not treat Hebrew letters as word characters.
|
|
55
|
+
if (/^(chapter|part|book|section|appendix|פרק|חלק|נספח)(?=[\s:.\d]|$)/iu.test(line) && previousBlank) {
|
|
56
|
+
return { line: index + 1, level: /^(part|book|חלק)(?=[\s:.\d]|$)/iu.test(line) ? 1 : 2, title: line };
|
|
57
|
+
}
|
|
58
|
+
if (/^\d+(\.\d+){0,2}\s+\S/.test(line) && previousBlank && line.length <= 80 && !/[.:;,]$/.test(line)) {
|
|
59
|
+
return { line: index + 1, level: (line.split(" ")[0].match(/\./g)?.length ?? 0) + 2, title: line };
|
|
60
|
+
}
|
|
61
|
+
if (previousBlank && line.length >= 4 && line.length <= 60 && /\p{Lu}/u.test(line) && line === line.toUpperCase() && /\p{L}{3}/u.test(line)) {
|
|
62
|
+
return { line: index + 1, level: 2, title: line };
|
|
41
63
|
}
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
/** The outline kept from all the headings found: at most 400 of them. */
|
|
67
|
+
function pickOutline(entries) {
|
|
42
68
|
if (entries.length <= MAX_OUTLINE_ENTRIES)
|
|
43
69
|
return entries;
|
|
44
|
-
// Keep the top
|
|
70
|
+
// Keep the top-level headings when there are at least 20 of them. A pool that fits is kept whole;
|
|
71
|
+
// a larger one is sampled evenly, so the outline still spans the document.
|
|
45
72
|
// A loop, not Math.min(...levels): spreading a few hundred thousand values overflows the stack.
|
|
46
73
|
let minLevel = Number.POSITIVE_INFINITY;
|
|
47
74
|
for (const entry of entries)
|
|
@@ -49,12 +76,15 @@ export function buildOutline(lines, format) {
|
|
|
49
76
|
minLevel = entry.level;
|
|
50
77
|
const top = entries.filter((entry) => entry.level === minLevel);
|
|
51
78
|
const pool = top.length >= 20 ? top : entries;
|
|
79
|
+
if (pool.length <= MAX_OUTLINE_ENTRIES)
|
|
80
|
+
return pool;
|
|
81
|
+
// The step is above 1 here, so each sampled index is greater than the one before it.
|
|
52
82
|
const step = pool.length / MAX_OUTLINE_ENTRIES;
|
|
53
|
-
return Array.from({ length:
|
|
83
|
+
return Array.from({ length: MAX_OUTLINE_ENTRIES }, (_, index) => pool[Math.floor(index * step)]);
|
|
54
84
|
}
|
|
55
85
|
/** Replaces the variable parts of a log message so repeated failures group together. */
|
|
56
86
|
export function logTemplate(line) {
|
|
57
|
-
|
|
87
|
+
const template = line
|
|
58
88
|
.replace(TIMESTAMP, "")
|
|
59
89
|
.replace(/^\W*\d{2}:\d{2}:\d{2}(?:[.,]\d+)?/, "")
|
|
60
90
|
.replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, "<id>")
|
|
@@ -63,44 +93,63 @@ export function logTemplate(line) {
|
|
|
63
93
|
.replace(/"[^"]{0,200}"|'[^']{0,200}'/g, "<s>")
|
|
64
94
|
.replace(/\d+(?:\.\d+)?/g, "<n>")
|
|
65
95
|
.replace(/\s+/g, " ")
|
|
66
|
-
.trim()
|
|
67
|
-
|
|
96
|
+
.trim();
|
|
97
|
+
return sliceWhole(template, 180);
|
|
68
98
|
}
|
|
69
99
|
export function buildLogProfile(lines) {
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
100
|
+
const profile = new LogProfiler();
|
|
101
|
+
for (let index = 0; index < lines.length; index++)
|
|
102
|
+
profile.add(lines[index] ?? "", index);
|
|
103
|
+
return profile.result();
|
|
104
|
+
}
|
|
105
|
+
/** `buildLogProfile`, the same result, with pauses for other requests while a large log is read. */
|
|
106
|
+
export async function buildLogProfileInSlices(lines, slicer) {
|
|
107
|
+
const profile = new LogProfiler();
|
|
74
108
|
for (let index = 0; index < lines.length; index++) {
|
|
75
|
-
|
|
109
|
+
profile.add(lines[index] ?? "", index);
|
|
110
|
+
if ((index & 4095) === 4095)
|
|
111
|
+
await slicer.maybePause();
|
|
112
|
+
}
|
|
113
|
+
return profile.result();
|
|
114
|
+
}
|
|
115
|
+
/** Builds a log profile one line at a time. */
|
|
116
|
+
class LogProfiler {
|
|
117
|
+
levels = {};
|
|
118
|
+
templates = new Map();
|
|
119
|
+
firstTimestamp;
|
|
120
|
+
lastTimestamp;
|
|
121
|
+
/** Adds line `index` (0-based). */
|
|
122
|
+
add(line, index) {
|
|
76
123
|
const stamp = TIMESTAMP.exec(line)?.[0];
|
|
77
124
|
if (stamp) {
|
|
78
|
-
firstTimestamp ??= stamp;
|
|
79
|
-
lastTimestamp = stamp;
|
|
125
|
+
this.firstTimestamp ??= stamp;
|
|
126
|
+
this.lastTimestamp = stamp;
|
|
80
127
|
}
|
|
81
128
|
const raw = LEVEL.exec(line)?.[1];
|
|
82
129
|
if (!raw)
|
|
83
|
-
|
|
130
|
+
return;
|
|
84
131
|
const level = LEVEL_NAMES[raw] ?? raw;
|
|
85
|
-
levels[level] = (levels[level] ?? 0) + 1;
|
|
132
|
+
this.levels[level] = (this.levels[level] ?? 0) + 1;
|
|
86
133
|
if (level !== "ERROR" && level !== "FATAL" && level !== "WARN")
|
|
87
|
-
|
|
134
|
+
return;
|
|
88
135
|
const template = logTemplate(line);
|
|
89
|
-
const existing = templates.get(template);
|
|
136
|
+
const existing = this.templates.get(template);
|
|
90
137
|
if (existing)
|
|
91
138
|
existing.count++;
|
|
92
|
-
else if (templates.size < MAX_TEMPLATES)
|
|
93
|
-
templates.set(template, { template, level, count: 1, firstLine: index + 1 });
|
|
139
|
+
else if (this.templates.size < MAX_TEMPLATES)
|
|
140
|
+
this.templates.set(template, { template, level, count: 1, firstLine: index + 1 });
|
|
141
|
+
}
|
|
142
|
+
result() {
|
|
143
|
+
const severity = (issue) => (issue.level === "FATAL" ? 2 : issue.level === "ERROR" ? 1 : 0);
|
|
144
|
+
const topIssues = [...this.templates.values()]
|
|
145
|
+
.sort((left, right) => severity(right) - severity(left) || right.count - left.count)
|
|
146
|
+
.slice(0, 15);
|
|
147
|
+
return {
|
|
148
|
+
levels: this.levels,
|
|
149
|
+
...(this.firstTimestamp ? { firstTimestamp: this.firstTimestamp } : {}),
|
|
150
|
+
...(this.lastTimestamp ? { lastTimestamp: this.lastTimestamp } : {}),
|
|
151
|
+
topIssues,
|
|
152
|
+
};
|
|
94
153
|
}
|
|
95
|
-
const severity = (issue) => (issue.level === "FATAL" ? 2 : issue.level === "ERROR" ? 1 : 0);
|
|
96
|
-
const topIssues = [...templates.values()]
|
|
97
|
-
.sort((left, right) => severity(right) - severity(left) || right.count - left.count)
|
|
98
|
-
.slice(0, 15);
|
|
99
|
-
return {
|
|
100
|
-
levels,
|
|
101
|
-
...(firstTimestamp ? { firstTimestamp } : {}),
|
|
102
|
-
...(lastTimestamp ? { lastTimestamp } : {}),
|
|
103
|
-
topIssues,
|
|
104
|
-
};
|
|
105
154
|
}
|
|
106
155
|
//# sourceMappingURL=analyze.js.map
|
package/dist/analyze.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analyze.js","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"analyze.js","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAGvC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,aAAa,GAAG,MAAM,CAAC;AAC7B,MAAM,SAAS,GAAG,6EAA6E,CAAC;AAChG,MAAM,oBAAoB,GAAG,qHAAqH,CAAC;AACnJ,MAAM,KAAK,GAAG,8DAA8D,CAAC;AAC7E,MAAM,WAAW,GAA2B,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAEjG,oFAAoF;AACpF,MAAM,UAAU,YAAY,CAAC,KAAe;IAC1C,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,GAAG,GAAG,EAAE,KAAK,EAAE;QAAE,IAAI,KAAK,CAAC,KAAK,CAAE,CAAC,IAAI,EAAE;YAAE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAE,CAAC,CAAC;IAC/H,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC;IACpC,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,mDAAmD,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,MAAM,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