llm-large-files 0.8.0 → 0.8.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 +51 -0
- package/README.md +2 -0
- package/dist/aggregate.d.ts +103 -0
- package/dist/aggregate.d.ts.map +1 -0
- package/dist/aggregate.js +651 -0
- package/dist/aggregate.js.map +1 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +17 -0
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +8 -1
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +40 -2
- package/dist/extract.js.map +1 -1
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +9 -2
- package/dist/library.js.map +1 -1
- package/dist/plan.d.ts +3 -1
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +17 -1
- package/dist/plan.js.map +1 -1
- package/dist/quality.d.ts +16 -0
- package/dist/quality.d.ts.map +1 -0
- package/dist/quality.js +157 -0
- package/dist/quality.js.map +1 -0
- package/dist/tools.d.ts +9 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +258 -5
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +20 -0
- package/dist/types.d.ts.map +1 -1
- package/docs/how-it-works.md +7 -0
- package/docs/reference/library.md +17 -6
- package/docs/reference/node.md +1 -1
- package/docs/reference/tools.md +99 -1
- package/package.json +1 -1
- package/src/aggregate.ts +674 -0
- package/src/evidence.ts +17 -0
- package/src/extract.ts +37 -2
- package/src/library.ts +9 -2
- package/src/plan.ts +17 -1
- package/src/quality.ts +146 -0
- package/src/tools.ts +249 -5
- package/src/types.ts +17 -0
package/src/tools.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { safeErrorMessage } from "./errors.js";
|
|
2
|
+
import { aggregateTable, FILTER_OPS, MAX_SHOWN_GROUPS, type AggregateRequest, type FilterOp } from "./aggregate.js";
|
|
2
3
|
import { GROUP_BY_VALUES, MAX_GROUP_KEYS, type GroupBy, type GroupResult } from "./groups.js";
|
|
3
4
|
import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
|
|
4
5
|
import { cutPdfPages } from "./pdf-pages.js";
|
|
@@ -42,6 +43,7 @@ export const TOOL_NAMES = {
|
|
|
42
43
|
overview: "get_document_overview",
|
|
43
44
|
analyze: "analyze_whole_document",
|
|
44
45
|
view: "view_pages",
|
|
46
|
+
aggregate: "aggregate_table",
|
|
45
47
|
} as const;
|
|
46
48
|
|
|
47
49
|
const documentId = { type: "string" as const, description: "The document_id from the file's card." };
|
|
@@ -98,6 +100,36 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
|
|
|
98
100
|
required: ["document_id", "task"],
|
|
99
101
|
},
|
|
100
102
|
},
|
|
103
|
+
aggregate: {
|
|
104
|
+
name: TOOL_NAMES.aggregate,
|
|
105
|
+
description: "Count, sum, average, or find the minimum or maximum over the rows of a table in an attached file: a CSV or TSV file, a sheet of an Excel workbook, or a table written as | cell | rows (in Word, PowerPoint, PDF or HTML files). It can keep only the rows that match filters, and group them by up to 3 columns (a date column by year, month or day). Its numbers are exact, as it reads every row: use it instead of reading rows to add them up or count them. Columns are named as in the table's header row; a letter (C) or a number (3) works too. Each group lists the lines of its first rows, to cite.",
|
|
106
|
+
parameters: {
|
|
107
|
+
type: "object",
|
|
108
|
+
properties: {
|
|
109
|
+
document_id: documentId,
|
|
110
|
+
table: { type: "string", description: "Which table: a sheet's name or number in a workbook, or a table's number in other files (1 is the first). Defaults to the first." },
|
|
111
|
+
metrics: { type: "array", items: { type: "string" }, description: "What to compute: \"count\", or an operation and a column: \"sum:Revenue\", \"avg:Price\", \"min:Date\", \"max:Amount\", \"count_distinct:Customer\". Defaults to [\"count\"]." },
|
|
112
|
+
group_by: { type: "array", items: { type: "string" }, description: "Up to 3 columns to group the rows by. A date column may end in \":year\", \":month\" or \":day\": \"Date:month\"." },
|
|
113
|
+
filters: {
|
|
114
|
+
type: "array",
|
|
115
|
+
description: "Keep only the rows that match all of these. Numbers compare as numbers, ISO dates (2026-03-01) as text, other text ignoring case.",
|
|
116
|
+
items: {
|
|
117
|
+
type: "object",
|
|
118
|
+
properties: {
|
|
119
|
+
column: { type: "string" },
|
|
120
|
+
op: { type: "string", enum: [...FILTER_OPS] },
|
|
121
|
+
value: { type: "string", description: "Not needed for empty and not_empty." },
|
|
122
|
+
},
|
|
123
|
+
required: ["column", "op"],
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
order_by: { type: "string", enum: ["metric", "key"], description: "\"metric\" (the default): the largest value of the first metric first; \"key\": by the values grouped by, in order (dates and months in time order)." },
|
|
127
|
+
limit: { type: "integer", description: `Groups to show, up to ${MAX_SHOWN_GROUPS} (default 50).` },
|
|
128
|
+
header_rows: { type: "integer", description: "Leave it out: the header is found by itself (a title row above it is skipped, and a header of two or three rows is joined, as \"Q1 / January\"). Only when a result's columns show the header was read wrong: how many rows it has, 0 to 5, below a title row." },
|
|
129
|
+
},
|
|
130
|
+
required: ["document_id"],
|
|
131
|
+
},
|
|
132
|
+
},
|
|
101
133
|
view: {
|
|
102
134
|
name: TOOL_NAMES.view,
|
|
103
135
|
description: `Look at pages of an attached PDF as they are printed. Use it when the answer depends on something the text of the file cannot show: a picture, photo, chart, diagram, map, handwriting, a stamp or signature, or how a page is laid out. It is not for reading text. Up to ${MAX_VIEW_PAGES} pages per call.`,
|
|
@@ -306,6 +338,142 @@ function groupedResult(base: ToolResult, counted: GroupResult, shown: number, li
|
|
|
306
338
|
return fit(build(kept, true), null, limit);
|
|
307
339
|
}
|
|
308
340
|
|
|
341
|
+
/** The most tables whose header rows one search result gives. */
|
|
342
|
+
const MAX_TABLE_HEADERS = 5;
|
|
343
|
+
/** Lines read at a time above a row of a `| cell |` table, to find the table's first row; and the most read in all. */
|
|
344
|
+
const HEADER_SEARCH_LINES = 500;
|
|
345
|
+
const MAX_HEADER_LOOKBACK = 20_000;
|
|
346
|
+
/** A section's title is given up to this many characters. */
|
|
347
|
+
const MAX_SECTION = 80;
|
|
348
|
+
|
|
349
|
+
const isPipeRow = (text: string) => {
|
|
350
|
+
const trimmed = text.trim();
|
|
351
|
+
return trimmed.length > 1 && trimmed.startsWith("|") && trimmed.endsWith("|");
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Where the matches of a search sit, so a hit can be understood without another read:
|
|
356
|
+
* - `section(line)`: the heading of the outline above a line ("2.1 Rent", "Sheet 2: Sales");
|
|
357
|
+
* - `headers`: the first row of each table a match is a row of: line 1 of a CSV file, the first
|
|
358
|
+
* row of a sheet of a workbook, the first row of a `| cell |` table elsewhere. A row of 0.8.0's
|
|
359
|
+
* `Row 812: | 4,200 |` means little without its header.
|
|
360
|
+
*/
|
|
361
|
+
async function locationsOf(document: DocumentSource, matches: LineMatch[]): Promise<{ section(line: number): string | undefined; headers: Array<{ line: number; text: string }> }> {
|
|
362
|
+
const { meta } = document;
|
|
363
|
+
// A store of your own may give metadata without an outline.
|
|
364
|
+
const outline = meta.format === "log" || meta.format === "json" || meta.format === "csv" || !Array.isArray(meta.outline) ? [] : meta.outline;
|
|
365
|
+
const section = (line: number): string | undefined => {
|
|
366
|
+
let low = 0;
|
|
367
|
+
let high = outline.length - 1;
|
|
368
|
+
let found = -1;
|
|
369
|
+
while (low <= high) {
|
|
370
|
+
const middle = (low + high) >> 1;
|
|
371
|
+
if (outline[middle]!.line <= line) {
|
|
372
|
+
found = middle;
|
|
373
|
+
low = middle + 1;
|
|
374
|
+
} else {
|
|
375
|
+
high = middle - 1;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return found === -1 ? undefined : sliceWhole(outline[found]!.title, MAX_SECTION);
|
|
379
|
+
};
|
|
380
|
+
const headers = new Map<number, string>();
|
|
381
|
+
const add = async (line: number) => {
|
|
382
|
+
if (headers.has(line) || headers.size >= MAX_TABLE_HEADERS) return;
|
|
383
|
+
const [text] = await document.readLines(line, line);
|
|
384
|
+
if (text !== undefined && text.trim()) headers.set(line, text.length > 400 ? `${sliceWhole(text, 400)}…` : text);
|
|
385
|
+
};
|
|
386
|
+
if (matches.length > 0) {
|
|
387
|
+
if (meta.format === "csv") {
|
|
388
|
+
if (matches.some((match) => match.line > 1)) await add(1);
|
|
389
|
+
} else if (meta.format === "xlsx") {
|
|
390
|
+
// A sheet's first row is two lines below its "## Sheet" heading, after its "Columns:" line.
|
|
391
|
+
const checked = new Set<number>();
|
|
392
|
+
for (const match of matches) {
|
|
393
|
+
const sheet = outline.filter((entry) => entry.title.startsWith("Sheet ") && entry.line <= match.line).at(-1);
|
|
394
|
+
if (!sheet || match.line <= sheet.line + 2 || checked.has(sheet.line)) continue;
|
|
395
|
+
checked.add(sheet.line);
|
|
396
|
+
const [first] = await document.readLines(sheet.line + 2, sheet.line + 2);
|
|
397
|
+
if (first?.startsWith("Row ")) await add(sheet.line + 2);
|
|
398
|
+
}
|
|
399
|
+
} else {
|
|
400
|
+
const seen = new Set<number>();
|
|
401
|
+
// The table found last: its first row, and its last line known to be a row. A later match in
|
|
402
|
+
// the same table is known by the rows between, read once, not by another look up the table.
|
|
403
|
+
let known: { first: number; end: number } | undefined;
|
|
404
|
+
for (const match of matches) {
|
|
405
|
+
if (!isPipeRow(match.text) || seen.size >= MAX_TABLE_HEADERS) continue;
|
|
406
|
+
if (known && match.line >= known.first && match.line <= known.end) continue;
|
|
407
|
+
if (known && match.line > known.end && match.line - known.end <= HEADER_SEARCH_LINES) {
|
|
408
|
+
const between = await document.readLines(known.end + 1, match.line);
|
|
409
|
+
if (between.every(isPipeRow)) {
|
|
410
|
+
known.end = match.line;
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
// Up the table a block at a time, to the first line that is not a row, or the file's start.
|
|
415
|
+
let line: number | undefined = match.line;
|
|
416
|
+
for (let looked = 0; ; ) {
|
|
417
|
+
const from: number = Math.max(1, line - HEADER_SEARCH_LINES);
|
|
418
|
+
const above = await document.readLines(from, line - 1);
|
|
419
|
+
let first = above.length;
|
|
420
|
+
while (first > 0 && isPipeRow(above[first - 1]!)) first--;
|
|
421
|
+
if (first > 0 || from === 1) {
|
|
422
|
+
line = from + first;
|
|
423
|
+
break;
|
|
424
|
+
}
|
|
425
|
+
line = from;
|
|
426
|
+
looked += above.length;
|
|
427
|
+
// A table longer than this: its first row is not looked for.
|
|
428
|
+
if (looked >= MAX_HEADER_LOOKBACK) {
|
|
429
|
+
line = undefined;
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (line === undefined) continue;
|
|
434
|
+
known = { first: line, end: match.line };
|
|
435
|
+
if (line === match.line || seen.has(line)) continue;
|
|
436
|
+
seen.add(line);
|
|
437
|
+
await add(line);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return { section: outline.length > 0 ? section : () => undefined, headers: [...headers].map(([line, text]) => ({ line, text })) };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** A list of strings the model sent: an array, or one string (which a model sometimes sends for a list of one). */
|
|
445
|
+
function stringList(value: unknown, name: string): string[] | undefined {
|
|
446
|
+
if (value === undefined || value === null || value === "") return undefined;
|
|
447
|
+
const list = Array.isArray(value) ? value : [value];
|
|
448
|
+
return list.map((item) => {
|
|
449
|
+
if (typeof item !== "string" && typeof item !== "number") throw new Error(`${name} must be a list of strings.`);
|
|
450
|
+
return String(item);
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** The arguments of an `aggregate_table` call as the tool reads them. */
|
|
455
|
+
export function aggregateRequest(args: Record<string, unknown>): AggregateRequest {
|
|
456
|
+
const rawFilters = args.filters === undefined || args.filters === null ? [] : Array.isArray(args.filters) ? args.filters : [args.filters];
|
|
457
|
+
const filters = rawFilters.map((filter) => {
|
|
458
|
+
const { column, op, value } = (filter ?? {}) as { column?: unknown; op?: unknown; value?: unknown };
|
|
459
|
+
if (typeof column !== "string" && typeof column !== "number") throw new Error("Each filter needs a column.");
|
|
460
|
+
if (typeof op !== "string" || !(FILTER_OPS as readonly string[]).includes(op)) throw new Error(`A filter's op must be one of ${FILTER_OPS.map((name) => `"${name}"`).join(", ")}.`);
|
|
461
|
+
return { column: String(column), op: op as FilterOp, ...(value !== undefined && value !== null ? { value: typeof value === "number" ? value : String(value) } : {}) };
|
|
462
|
+
});
|
|
463
|
+
const table = typeof args.table === "number" || (typeof args.table === "string" && args.table.trim()) ? args.table as string | number : undefined;
|
|
464
|
+
const groupBy = stringList(args.group_by, "group_by");
|
|
465
|
+
const metrics = stringList(args.metrics, "metrics");
|
|
466
|
+
return {
|
|
467
|
+
...(table !== undefined ? { table } : {}),
|
|
468
|
+
...(filters.length > 0 ? { filters } : {}),
|
|
469
|
+
...(groupBy ? { groupBy } : {}),
|
|
470
|
+
...(metrics ? { metrics } : {}),
|
|
471
|
+
orderBy: args.order_by === "key" ? "key" : "metric",
|
|
472
|
+
limit: integer(args.limit, 50, 1, MAX_SHOWN_GROUPS),
|
|
473
|
+
...(args.header_rows !== undefined && args.header_rows !== null && args.header_rows !== "" ? { headerRows: integer(args.header_rows, 1, 0, 5) } : {}),
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
309
477
|
const searchMode = (mode: unknown): "keywords" | "exact" | "regex" => (mode === "exact" || mode === "regex" ? mode : "keywords");
|
|
310
478
|
|
|
311
479
|
/** `group_by` as the search reads it: undefined when not given. A value it does not know is an error. */
|
|
@@ -375,6 +543,13 @@ export function toolCallKey(name: string, args: Record<string, unknown>): string
|
|
|
375
543
|
: [name, id, args.query, mode, groupBy ? integer(args.max_results, DEFAULT_GROUPS, 1, MAX_GROUPS) : integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS), groupBy ? 0 : integer(args.context_lines, 0, 0, 5), caseSensitive, ...scope]);
|
|
376
544
|
}
|
|
377
545
|
if (name === TOOL_NAMES.read) return JSON.stringify([name, id, ...requestedLines(args)]);
|
|
546
|
+
if (name === TOOL_NAMES.aggregate) {
|
|
547
|
+
try {
|
|
548
|
+
return JSON.stringify([name, id, aggregateRequest(args)]);
|
|
549
|
+
} catch {
|
|
550
|
+
return undefined;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
378
553
|
if (name === TOOL_NAMES.overview) return JSON.stringify([name, id]);
|
|
379
554
|
return undefined;
|
|
380
555
|
}
|
|
@@ -460,6 +635,10 @@ export function toolResultSummary(label: string, result: ToolResult): string {
|
|
|
460
635
|
return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}${groups}`;
|
|
461
636
|
}
|
|
462
637
|
if (Array.isArray(result.passages)) return ` — ${result.passages.length} ${plural(result.passages.length, "passage")}`;
|
|
638
|
+
if (typeof result.rows_matched === "number") {
|
|
639
|
+
const groups = typeof result.total_groups === "number" ? `, ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
|
|
640
|
+
return ` — ${result.rows_matched.toLocaleString("en-US")} ${plural(result.rows_matched, "row")}${groups}`;
|
|
641
|
+
}
|
|
463
642
|
if (typeof result.parts_read === "number") {
|
|
464
643
|
const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
465
644
|
return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
|
|
@@ -527,6 +706,11 @@ export function createDocumentTools(options: {
|
|
|
527
706
|
viewableIds?: string[];
|
|
528
707
|
/** Loads the uploaded file of a document, for `view_pages`. */
|
|
529
708
|
loadOriginal?(documentId: string): Promise<Uint8Array | undefined>;
|
|
709
|
+
/**
|
|
710
|
+
* True when a document may hold a table (a CSV, a workbook, a document with `| cell |` rows):
|
|
711
|
+
* `aggregate_table` is then declared. A call of it is answered either way. Defaults to false.
|
|
712
|
+
*/
|
|
713
|
+
tables?: boolean;
|
|
530
714
|
}): ToolSet {
|
|
531
715
|
const allowed = new Set(options.documentIds);
|
|
532
716
|
const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
|
|
@@ -534,10 +718,12 @@ export function createDocumentTools(options: {
|
|
|
534
718
|
// The text tools are left out only when there are pages to look at and no document to search.
|
|
535
719
|
const textTools = allowed.size > 0 || viewable.size === 0;
|
|
536
720
|
const declarations = [
|
|
537
|
-
...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
|
|
721
|
+
...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.tables ? [DECLARATIONS.aggregate] : []), ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
|
|
538
722
|
...(viewable.size > 0 ? [DECLARATIONS.view] : []),
|
|
539
723
|
];
|
|
540
724
|
const known = new Set(declarations.map((declaration) => declaration.name));
|
|
725
|
+
// Answered for any document, declared or not: a model may know the tool from earlier in the conversation.
|
|
726
|
+
if (textTools) known.add(TOOL_NAMES.aggregate);
|
|
541
727
|
// Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
|
|
542
728
|
if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
|
|
543
729
|
const cap = options.budget.toolResultCharacters;
|
|
@@ -648,13 +834,22 @@ export function createDocumentTools(options: {
|
|
|
648
834
|
});
|
|
649
835
|
};
|
|
650
836
|
const result = await (regex ? inRegexTurn(grep) : grep());
|
|
837
|
+
const shownMatches = [...(result.first ? [result.first] : []), ...result.matches, ...(result.last ? [result.last] : [])];
|
|
838
|
+
const where = await locationsOf(document, shownMatches);
|
|
651
839
|
const placed = (match: LineMatch): LineMatch => {
|
|
652
|
-
|
|
840
|
+
const page = paged ? document.pageOfLine(match.line) : undefined;
|
|
841
|
+
const section = where.section(match.line);
|
|
842
|
+
if (!page && !section) return match;
|
|
653
843
|
const { line, ...rest } = match;
|
|
654
|
-
|
|
655
|
-
|
|
844
|
+
return { line, ...(page ? { page } : {}), ...(section ? { section } : {}), ...rest };
|
|
845
|
+
};
|
|
846
|
+
const base = {
|
|
847
|
+
document: document.meta.name,
|
|
848
|
+
mode,
|
|
849
|
+
...searched,
|
|
850
|
+
total_matching_lines: result.totalMatchingLines,
|
|
851
|
+
...(where.headers.length > 0 ? { table_headers: where.headers } : {}),
|
|
656
852
|
};
|
|
657
|
-
const base = { document: document.meta.name, mode, ...searched, total_matching_lines: result.totalMatchingLines };
|
|
658
853
|
const stopped = result.stoppedEarly ? { note: "The scan stopped early; the counts are lower bounds." } : {};
|
|
659
854
|
if (result.groups) return groupedResult({ ...base, group_by: groupBy!, ...stopped }, result.groups, shownGroups, limit);
|
|
660
855
|
const matches = result.matches.map(placed);
|
|
@@ -733,6 +928,41 @@ export function createDocumentTools(options: {
|
|
|
733
928
|
}, "outline", limit);
|
|
734
929
|
},
|
|
735
930
|
|
|
931
|
+
async [TOOL_NAMES.aggregate](args, limits) {
|
|
932
|
+
const limit = limitOf(limits);
|
|
933
|
+
const document = await documentFor(args);
|
|
934
|
+
const request = aggregateRequest(args);
|
|
935
|
+
const result = await aggregateTable(document, request, options.signal);
|
|
936
|
+
const groups = result.groups.map((group) => ({
|
|
937
|
+
...(Object.keys(group.key).length > 0 ? { group: group.key } : {}),
|
|
938
|
+
...group.values,
|
|
939
|
+
...(group.values.count === undefined ? { rows: group.count } : {}),
|
|
940
|
+
lines: group.lines,
|
|
941
|
+
}));
|
|
942
|
+
const shownColumns = result.columns.slice(0, 60);
|
|
943
|
+
const base = {
|
|
944
|
+
document: document.meta.name,
|
|
945
|
+
table: result.table,
|
|
946
|
+
...(result.tables > 1 ? { tables_in_file: result.tables } : {}),
|
|
947
|
+
header_line: result.headerLine,
|
|
948
|
+
...(result.headerRows !== 1 ? { header_rows: result.headerRows } : {}),
|
|
949
|
+
...(result.title !== undefined ? { title: result.title } : {}),
|
|
950
|
+
columns: result.columns.length > shownColumns.length ? [...shownColumns, `… ${result.columns.length - shownColumns.length} more`] : shownColumns,
|
|
951
|
+
rows_read: result.rowsRead,
|
|
952
|
+
rows_matched: result.rowsMatched,
|
|
953
|
+
...(result.totalGroups > 1 || (request.groupBy?.length ?? 0) > 0 ? { total_groups: result.totalGroups } : {}),
|
|
954
|
+
...(result.otherRows > 0 ? { other_rows: result.otherRows, other_note: `Rows of groups past the first ${MAX_GROUP_KEYS.toLocaleString("en-US")} found.` } : {}),
|
|
955
|
+
...(Object.keys(result.notNumbers).length > 0 ? { values_not_numbers: result.notNumbers, values_note: "Cells of these columns that are not numbers were left out of the metric." } : {}),
|
|
956
|
+
...(result.repeatedHeaders > 0 ? { repeated_header_rows: result.repeatedHeaders } : {}),
|
|
957
|
+
...(result.distinctCapped ? { distinct_note: "count_distinct stopped telling values apart after 1,000,000 in all: its counts are lower bounds. Filter, or group by fewer values." } : {}),
|
|
958
|
+
...(result.irregularRows > 0 ? { irregular_rows: result.irregularRows, irregular_note: "Rows with values past the header's columns: check columns and header_rows." } : {}),
|
|
959
|
+
};
|
|
960
|
+
const note = groups.length < result.totalGroups
|
|
961
|
+
? { note: `${groups.length} of the ${result.totalGroups} groups are shown, ${request.orderBy === "key" ? "in the order of their values" : "the largest first"}. Raise limit, or filter, for the others.` }
|
|
962
|
+
: {};
|
|
963
|
+
return fit({ ...base, ...note, groups }, "groups", limit);
|
|
964
|
+
},
|
|
965
|
+
|
|
736
966
|
async [TOOL_NAMES.analyze](args, limits, hooks) {
|
|
737
967
|
if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
|
|
738
968
|
const document = await documentFor(args);
|
|
@@ -895,6 +1125,20 @@ export function createDocumentTools(options: {
|
|
|
895
1125
|
return `Read ${file} lines ${start}${end}`;
|
|
896
1126
|
}
|
|
897
1127
|
if (name === TOOL_NAMES.overview) return `Overview of ${file}`;
|
|
1128
|
+
if (name === TOOL_NAMES.aggregate) {
|
|
1129
|
+
const request = (() => {
|
|
1130
|
+
try {
|
|
1131
|
+
return aggregateRequest(args);
|
|
1132
|
+
} catch {
|
|
1133
|
+
return {} as AggregateRequest;
|
|
1134
|
+
}
|
|
1135
|
+
})();
|
|
1136
|
+
const metrics = (request.metrics?.length ? request.metrics : ["count"]).join(", ");
|
|
1137
|
+
const by = request.groupBy?.length ? ` by ${request.groupBy.join(", ")}` : "";
|
|
1138
|
+
const where = request.filters?.length ? ` where ${request.filters.map((filter) => `${filter.column} ${filter.op}${filter.value !== undefined && filter.value !== "" ? ` ${filter.value}` : ""}`).join(" and ")}` : "";
|
|
1139
|
+
const table = request.table !== undefined && request.table !== "" ? ` (${typeof request.table === "number" ? `table ${request.table}` : request.table})` : "";
|
|
1140
|
+
return sliceWhole(`Aggregate ${file}${table}: ${metrics}${by}${where}`, 200);
|
|
1141
|
+
}
|
|
898
1142
|
if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
|
|
899
1143
|
return name;
|
|
900
1144
|
},
|
package/src/types.ts
CHANGED
|
@@ -69,6 +69,23 @@ export type DocumentMeta = {
|
|
|
69
69
|
originalKept?: boolean;
|
|
70
70
|
outline: OutlineEntry[];
|
|
71
71
|
logProfile?: LogProfile;
|
|
72
|
+
/**
|
|
73
|
+
* The pages of a PDF that have no text at all: scans, photos, charts. Up to 200 are listed.
|
|
74
|
+
* Absent when there are none, and on documents from before 0.8.1.
|
|
75
|
+
*/
|
|
76
|
+
pagesWithoutText?: number[];
|
|
77
|
+
/**
|
|
78
|
+
* The pages of a PDF whose text looks garbled: few letters and digits among their characters, or
|
|
79
|
+
* many replacement characters (a font without a Unicode map). Up to 200 are listed. Absent when
|
|
80
|
+
* there are none, and on documents from before 0.8.1.
|
|
81
|
+
*/
|
|
82
|
+
garbledPages?: number[];
|
|
83
|
+
/**
|
|
84
|
+
* The scripts the text is written in, by their share of its letters in percent ("Hebrew" 81,
|
|
85
|
+
* "Latin" 19), from its first 2 MB, those of 5% or more. Absent for a text in Latin letters alone,
|
|
86
|
+
* one with few letters, and documents from before 0.8.1.
|
|
87
|
+
*/
|
|
88
|
+
scripts?: Array<{ script: string; percent: number }>;
|
|
72
89
|
createdAt: string;
|
|
73
90
|
expiresAt: string;
|
|
74
91
|
};
|