llm-large-files 0.3.6 → 0.4.1
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 +115 -0
- package/dist/cache.d.ts +49 -0
- package/dist/cache.d.ts.map +1 -0
- package/dist/cache.js +110 -0
- package/dist/cache.js.map +1 -0
- package/dist/errors.d.ts +21 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +44 -0
- package/dist/errors.js.map +1 -0
- package/dist/gemini/chat.d.ts +5 -0
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +17 -1
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -0
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +110 -25
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +1 -1
- package/dist/gemini/index.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +48 -2
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +192 -52
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +20 -0
- package/dist/limiter.d.ts.map +1 -0
- package/dist/limiter.js +55 -0
- package/dist/limiter.js.map +1 -0
- package/dist/map-reduce.d.ts +14 -4
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +99 -33
- package/dist/map-reduce.js.map +1 -1
- package/dist/plan.d.ts +25 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +51 -13
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts +102 -0
- package/dist/ranged.d.ts.map +1 -0
- package/dist/ranged.js +321 -0
- package/dist/ranged.js.map +1 -0
- package/dist/search.d.ts +93 -15
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +472 -131
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +26 -2
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +181 -21
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +64 -0
- package/dist/text-index.d.ts.map +1 -0
- package/dist/text-index.js +211 -0
- package/dist/text-index.js.map +1 -0
- package/dist/text.d.ts +14 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +50 -16
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +14 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +53 -21
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +20 -0
- package/dist/types.d.ts.map +1 -1
- package/docs/api.md +24 -10
- package/docs/configuration.md +50 -3
- package/docs/getting-started.md +2 -0
- package/docs/how-it-works.md +11 -3
- package/docs/security.md +21 -3
- package/package.json +7 -3
- package/src/cache.ts +107 -0
- package/src/errors.ts +42 -0
- package/src/gemini/chat.ts +22 -1
- package/src/gemini/generate.ts +107 -25
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +3 -2
- package/src/library.ts +229 -50
- package/src/limiter.ts +51 -0
- package/src/map-reduce.ts +101 -33
- package/src/plan.ts +54 -14
- package/src/ranged.ts +355 -0
- package/src/search.ts +524 -121
- package/src/stores.ts +178 -23
- package/src/text-index.ts +228 -0
- package/src/text.ts +46 -13
- package/src/tools.ts +61 -23
- package/src/types.ts +20 -0
package/src/tools.ts
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { safeErrorMessage } from "./errors.js";
|
|
2
|
+
import { analyzeWholeDocument } from "./map-reduce.js";
|
|
2
3
|
import { cutPdfPages } from "./pdf-pages.js";
|
|
3
|
-
import {
|
|
4
|
-
import { formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
4
|
+
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource } from "./search.js";
|
|
5
|
+
import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
5
6
|
import type { Budget, GenerateText, ProgressListener, ToolDeclaration, ToolFileLimits, ToolOutput, ToolResult, ToolSet } from "./types.js";
|
|
6
7
|
|
|
7
8
|
const DEFAULT_READ_LINES = 200;
|
|
8
9
|
const MAX_READ_LINES = 600;
|
|
9
10
|
/** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
|
|
10
11
|
export const MAX_VIEW_PAGES = 5;
|
|
12
|
+
/**
|
|
13
|
+
* The time the regex searches of one tool set (one question, in `askGemini`) may take together,
|
|
14
|
+
* unless `regexBudgetMs` says otherwise. An ordinary search of a 60 MB log takes about 0.15 s.
|
|
15
|
+
*/
|
|
16
|
+
export const REGEX_BUDGET_MS = 6_000;
|
|
11
17
|
/** Below this, no page fits: a cut of one page of plain text is larger. */
|
|
12
18
|
const MIN_FILE_BYTES = 1_024;
|
|
13
19
|
|
|
@@ -153,7 +159,7 @@ export function toolResultSummary(label: string, result: ToolResult): string {
|
|
|
153
159
|
|
|
154
160
|
export function createDocumentTools(options: {
|
|
155
161
|
/** Loads a document the tools may access. Return undefined for anything out of scope. */
|
|
156
|
-
load(documentId: string): Promise<
|
|
162
|
+
load(documentId: string): Promise<DocumentSource | undefined>;
|
|
157
163
|
documentIds: string[];
|
|
158
164
|
/** File names by document ID, so `describe` can name files before they are loaded. */
|
|
159
165
|
names?: Record<string, string>;
|
|
@@ -161,6 +167,13 @@ export function createDocumentTools(options: {
|
|
|
161
167
|
generate?: GenerateText;
|
|
162
168
|
onProgress?: ProgressListener;
|
|
163
169
|
signal?: AbortSignal;
|
|
170
|
+
/** The most time, in milliseconds, that the regex searches of this tool set may take together. Defaults to `REGEX_BUDGET_MS`. */
|
|
171
|
+
regexBudgetMs?: number;
|
|
172
|
+
/**
|
|
173
|
+
* False when every document is too large for a whole-document read: `analyze_whole_document` is
|
|
174
|
+
* then not declared. A call of it still answers with the reason. Defaults to true.
|
|
175
|
+
*/
|
|
176
|
+
wholeReads?: boolean;
|
|
164
177
|
/**
|
|
165
178
|
* PDFs whose pages `view_pages` may show. The tool is declared only when there is at least one
|
|
166
179
|
* and `loadOriginal` is given. They need not be among `documentIds`: a PDF whose text is in the
|
|
@@ -176,15 +189,21 @@ export function createDocumentTools(options: {
|
|
|
176
189
|
// The text tools are left out only when there are pages to look at and no document to search.
|
|
177
190
|
const textTools = allowed.size > 0 || viewable.size === 0;
|
|
178
191
|
const declarations = [
|
|
179
|
-
...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.generate ? [DECLARATIONS.analyze] : [])] : []),
|
|
192
|
+
...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
|
|
180
193
|
...(viewable.size > 0 ? [DECLARATIONS.view] : []),
|
|
181
194
|
];
|
|
182
195
|
const known = new Set(declarations.map((declaration) => declaration.name));
|
|
196
|
+
// Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
|
|
197
|
+
if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
|
|
183
198
|
const limit = options.budget.toolResultCharacters;
|
|
199
|
+
// The model writes the regex, and a file it reads can ask for a slow one: the time is counted
|
|
200
|
+
// over every search of this tool set, not only within one.
|
|
201
|
+
const regexBudget = Math.max(0, options.regexBudgetMs ?? REGEX_BUDGET_MS);
|
|
202
|
+
const regexClock = { usedMs: 0 };
|
|
184
203
|
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
185
204
|
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
186
205
|
|
|
187
|
-
async function documentFor(args: Record<string, unknown>): Promise<
|
|
206
|
+
async function documentFor(args: Record<string, unknown>): Promise<DocumentSource> {
|
|
188
207
|
const id = text(args.document_id, "document_id");
|
|
189
208
|
// Scope check: a model can only reach files attached to this conversation.
|
|
190
209
|
if (!allowed.has(id)) throw new Error(`Unknown document_id ${id}. Use an ID from a file card.`);
|
|
@@ -204,27 +223,35 @@ export function createDocumentTools(options: {
|
|
|
204
223
|
const paged = viewable.has(document.meta.id);
|
|
205
224
|
if (mode === "keywords") {
|
|
206
225
|
const topK = integer(args.max_results, 5, 1, 10);
|
|
207
|
-
const ranked =
|
|
226
|
+
const ranked = await rankSource(document, query, topK, options.signal);
|
|
227
|
+
const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
|
|
208
228
|
return fit({
|
|
209
229
|
document: document.meta.name,
|
|
210
230
|
mode,
|
|
211
|
-
passages: ranked.map((passage) => {
|
|
231
|
+
passages: ranked.map((passage, index) => {
|
|
212
232
|
const pages = paged ? document.pagesOfLines(passage.from, passage.to) : undefined;
|
|
213
233
|
return {
|
|
214
234
|
lines: `${passage.from}-${passage.to}`,
|
|
215
235
|
...(pages ? { pages } : {}),
|
|
216
236
|
score: passage.score,
|
|
217
|
-
text:
|
|
237
|
+
text: numberLines(texts[index]!, passage.from),
|
|
218
238
|
};
|
|
219
239
|
}),
|
|
220
240
|
...(ranked.length === 0 ? { note: "No passage contains these keywords. Try other words, synonyms, or exact mode." } : {}),
|
|
221
241
|
}, "passages", limit);
|
|
222
242
|
}
|
|
223
|
-
const
|
|
224
|
-
|
|
243
|
+
const regex = mode === "regex";
|
|
244
|
+
const regexLeft = regexBudget - regexClock.usedMs;
|
|
245
|
+
if (regex && regexLeft <= 0) {
|
|
246
|
+
throw new Error("The time for regex searches is used up for this answer. Search with mode \"exact\" or \"keywords\" instead.");
|
|
247
|
+
}
|
|
248
|
+
const result = await grepSource(document, query, {
|
|
249
|
+
regex,
|
|
225
250
|
caseSensitive: args.case_sensitive === true,
|
|
226
251
|
maxResults: integer(args.max_results, 20, 1, 50),
|
|
227
252
|
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
253
|
+
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
254
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
228
255
|
});
|
|
229
256
|
return fit({
|
|
230
257
|
document: document.meta.name,
|
|
@@ -240,14 +267,18 @@ export function createDocumentTools(options: {
|
|
|
240
267
|
|
|
241
268
|
async [TOOL_NAMES.read](args) {
|
|
242
269
|
const document = await documentFor(args);
|
|
243
|
-
const total = document.
|
|
270
|
+
const total = document.lineCount;
|
|
244
271
|
const start = integer(args.start_line, 1, 1, total);
|
|
245
272
|
const end = integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, Math.min(total, start + MAX_READ_LINES - 1));
|
|
273
|
+
// One read for the range asked; trimming to the size limit works on what was read.
|
|
274
|
+
const read = await document.readLines(start, end);
|
|
246
275
|
let to = end;
|
|
247
|
-
let body =
|
|
248
|
-
|
|
276
|
+
let body = numberLines(read, start);
|
|
277
|
+
// The limit is on the result as it is sent, as JSON: quotes, tabs and line breaks each take two characters there.
|
|
278
|
+
const fits = (text: string) => JSON.stringify(text).length <= limit - 500;
|
|
279
|
+
while (!fits(body) && to > start) {
|
|
249
280
|
to = start + Math.max(0, Math.floor((to - start) * 0.7));
|
|
250
|
-
body =
|
|
281
|
+
body = numberLines(read.slice(0, to - start + 1), start);
|
|
251
282
|
}
|
|
252
283
|
const pages = viewable.has(document.meta.id) ? document.pagesOfLines(start, to) : undefined;
|
|
253
284
|
return {
|
|
@@ -255,15 +286,20 @@ export function createDocumentTools(options: {
|
|
|
255
286
|
lines: `${start}-${to}`,
|
|
256
287
|
...(pages ? { pages } : {}),
|
|
257
288
|
total_lines: total,
|
|
258
|
-
text: body.slice(0, limit - 500),
|
|
289
|
+
text: fits(body) ? body : body.slice(0, Math.floor((limit - 500) / 2)),
|
|
259
290
|
...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
|
|
260
291
|
};
|
|
261
292
|
},
|
|
262
293
|
|
|
263
294
|
async [TOOL_NAMES.overview](args) {
|
|
264
295
|
const document = await documentFor(args);
|
|
265
|
-
const { meta,
|
|
266
|
-
const tail = Math.max(1,
|
|
296
|
+
const { meta, lineCount } = document;
|
|
297
|
+
const tail = Math.max(1, lineCount - 19);
|
|
298
|
+
// Counting the parts means reading the whole text, for a number that only says how costly a
|
|
299
|
+
// whole-document read is. It is worked out from the metadata instead, to within a part or
|
|
300
|
+
// two; the read itself counts them.
|
|
301
|
+
const parts = estimateParts(meta, options.budget);
|
|
302
|
+
const first = Math.min(30, lineCount);
|
|
267
303
|
return fit({
|
|
268
304
|
document: meta.name,
|
|
269
305
|
format: meta.format,
|
|
@@ -271,10 +307,11 @@ export function createDocumentTools(options: {
|
|
|
271
307
|
lines: meta.lines,
|
|
272
308
|
estimated_tokens: meta.estimatedTokens,
|
|
273
309
|
...(meta.pages ? { pages: meta.pages } : {}),
|
|
274
|
-
parts_for_whole_document_analysis:
|
|
310
|
+
parts_for_whole_document_analysis: parts,
|
|
311
|
+
...(parts > options.budget.maxMapChunks ? { whole_document_analysis: `Not available for this file: it would take about ${parts} parts, and the limit is ${options.budget.maxMapChunks}. Use search_document and read_document.` } : {}),
|
|
275
312
|
...(meta.logProfile ? { log_profile: meta.logProfile } : {}),
|
|
276
|
-
first_lines:
|
|
277
|
-
last_lines:
|
|
313
|
+
first_lines: numberLines(await document.readLines(1, first), 1),
|
|
314
|
+
last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
|
|
278
315
|
outline: meta.outline.length ? outlineLines(meta.outline) : [],
|
|
279
316
|
}, "outline", limit);
|
|
280
317
|
},
|
|
@@ -335,7 +372,7 @@ export function createDocumentTools(options: {
|
|
|
335
372
|
try {
|
|
336
373
|
cut = await cutPdfPages(original, from, Math.min(asked, from + mostPages - 1), maxBytes, total);
|
|
337
374
|
} catch (error) {
|
|
338
|
-
throw new Error(`${file}: ${
|
|
375
|
+
throw new Error(`${file}: ${safeErrorMessage(error)}`);
|
|
339
376
|
}
|
|
340
377
|
const pages = pageRange(cut.from, cut.to);
|
|
341
378
|
const shown = cut.to - cut.from + 1;
|
|
@@ -354,7 +391,8 @@ export function createDocumentTools(options: {
|
|
|
354
391
|
};
|
|
355
392
|
}
|
|
356
393
|
|
|
357
|
-
|
|
394
|
+
// What a tool could not do goes to the model, and from there to a user's screen: never a server path.
|
|
395
|
+
const failure = (error: unknown): ToolResult => ({ error: safeErrorMessage(error) });
|
|
358
396
|
|
|
359
397
|
async function execute(name: string, args: Record<string, unknown>): Promise<ToolResult> {
|
|
360
398
|
if (!known.has(name)) return { error: `Unknown tool ${name}.` };
|
package/src/types.ts
CHANGED
|
@@ -38,6 +38,11 @@ export type DocumentMeta = {
|
|
|
38
38
|
bytes: number;
|
|
39
39
|
/** UTF-8 size of the extracted text. */
|
|
40
40
|
textBytes: number;
|
|
41
|
+
/**
|
|
42
|
+
* Bytes the text takes inside a JSON request body, with the escapes JSON adds. Absent on a
|
|
43
|
+
* document ingested before 0.4.1: planning then assumes 8% more than `textBytes`.
|
|
44
|
+
*/
|
|
45
|
+
jsonBytes?: number;
|
|
41
46
|
characters: number;
|
|
42
47
|
lines: number;
|
|
43
48
|
estimatedTokens: number;
|
|
@@ -87,6 +92,21 @@ export interface DocumentStore {
|
|
|
87
92
|
putOriginal?(id: string, bytes: Uint8Array): Promise<void>;
|
|
88
93
|
/** The uploaded file, or undefined when none was kept or the document is unknown or expired. */
|
|
89
94
|
getOriginal?(id: string): Promise<Uint8Array | undefined>;
|
|
95
|
+
/**
|
|
96
|
+
* Bytes `start` (inclusive) to `end` (exclusive) of the stored text, as UTF-8. Optional: with it,
|
|
97
|
+
* a tool call reads only the lines it needs, and a search reads the text a piece at a time,
|
|
98
|
+
* instead of loading the whole text into memory. Return fewer bytes at the end of the text, and
|
|
99
|
+
* undefined when the document is gone. It is called only after `getMeta` found the document.
|
|
100
|
+
*/
|
|
101
|
+
readTextRange?(id: string, start: number, end: number): Promise<Uint8Array | undefined>;
|
|
102
|
+
/**
|
|
103
|
+
* Keeps the line index of a document (a few bytes a line), so that reading by range needs no
|
|
104
|
+
* pass over the text first. Called at ingest, before `put`, and when an older document without an
|
|
105
|
+
* index is first read. Optional, and only useful with `readTextRange`.
|
|
106
|
+
*/
|
|
107
|
+
putIndex?(id: string, index: Uint8Array): Promise<void>;
|
|
108
|
+
/** The index kept by `putIndex`, or undefined. A damaged one is noticed and built again. */
|
|
109
|
+
getIndex?(id: string): Promise<Uint8Array | undefined>;
|
|
90
110
|
}
|
|
91
111
|
|
|
92
112
|
export type ExtractedText = { text: string; pages?: number };
|