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/src/evidence.ts CHANGED
@@ -96,6 +96,13 @@ export function evidenceOf(call: ToolCall, result: ToolResult): Evidence | undef
96
96
  }
97
97
  case TOOL_NAMES.analyze:
98
98
  return { ...entry, whole: true, ...(typeof call.args.task === "string" ? { query: call.args.task } : {}) };
99
+ case TOOL_NAMES.aggregate: {
100
+ // The rows read are all of the table; what can be cited is the header and each group's first rows.
101
+ const groups = (Array.isArray(result.groups) ? result.groups : []) as Array<{ lines?: unknown }>;
102
+ const lines = groups.flatMap((group) => (Array.isArray(group.lines) ? group.lines.filter((line): line is number => typeof line === "number") : []));
103
+ const header = typeof result.header_line === "number" && result.header_line > 0 ? [result.header_line] : [];
104
+ return withRanges([...header, ...lines].map((line): NumberRange => [line, line]), []);
105
+ }
99
106
  case TOOL_NAMES.view:
100
107
  return withRanges([], defined([rangeOf(result.pages)]));
101
108
  default:
@@ -147,6 +154,16 @@ export function stubResult(call: ToolCall, result: ToolResult, hadFiles = false)
147
154
  ...(Array.isArray(result.groups) ? { groups: result.groups.slice(0, KEPT_GROUPS) } : {}),
148
155
  note: "The results of this search were shown to you earlier and were dropped from the conversation to make room. Read the lines listed here with read_document, or search again, if you need them.",
149
156
  };
157
+ case TOOL_NAMES.aggregate:
158
+ // Counts cannot be read again from lines: the largest groups are kept as they are.
159
+ return {
160
+ ...base,
161
+ ...(typeof result.table === "string" ? { table: result.table } : {}),
162
+ ...(typeof result.rows_matched === "number" ? { rows_matched: result.rows_matched } : {}),
163
+ ...(typeof result.total_groups === "number" ? { total_groups: result.total_groups } : {}),
164
+ ...(Array.isArray(result.groups) ? { groups: result.groups.slice(0, KEPT_GROUPS) } : {}),
165
+ note: "This result was shown to you earlier and was shortened to make room: the largest groups are kept. Run aggregate_table again for the others.",
166
+ };
150
167
  case TOOL_NAMES.analyze: {
151
168
  const answer = typeof result.answer === "string" ? result.answer : "";
152
169
  return {
package/src/extract.ts CHANGED
@@ -43,12 +43,47 @@ const MIME_FORMATS: Record<string, DocumentFormat> = {
43
43
  * come from the upload: only the tables' own keys count, not "constructor" or "__proto__", which
44
44
  * every object has.
45
45
  */
46
- export function detectFormat(name: string, mimeType: string): DocumentFormat {
46
+ export function detectFormat(name: string, mimeType: string, bytes?: Uint8Array): DocumentFormat {
47
47
  const extension = name.toLowerCase().split(".").at(-1) ?? "";
48
48
  const mime = mimeType.toLowerCase();
49
- return (Object.hasOwn(EXTENSION_FORMATS, extension) ? EXTENSION_FORMATS[extension] : undefined)
49
+ const named = (Object.hasOwn(EXTENSION_FORMATS, extension) ? EXTENSION_FORMATS[extension] : undefined)
50
50
  ?? (Object.hasOwn(MIME_FORMATS, mime) ? MIME_FORMATS[mime] : undefined)
51
51
  ?? "text";
52
+ // A name that says text ("notes.txt") is taken at its word.
53
+ return named === "text" && bytes && extension !== "txt" ? sniffFormat(bytes) ?? named : named;
54
+ }
55
+
56
+ /** Where the part names of an Office file are looked for: its directory at the end, and its first parts. */
57
+ const SNIFFED_HEAD = 64 * 1024;
58
+ const SNIFFED_TAIL = 1024 * 1024;
59
+
60
+ /**
61
+ * The format of a file whose name and type say nothing (no extension, "application/octet-stream"),
62
+ * from its bytes: a PDF by its header, a DOCX, PPTX or XLSX by the names of its parts, an HTML page
63
+ * by its first tag. Undefined for anything else, which is read as text. A DOCX sent without its
64
+ * extension was told "This file is a ZIP archive".
65
+ */
66
+ export function sniffFormat(bytes: Uint8Array): DocumentFormat | undefined {
67
+ const head = latin1(bytes.subarray(0, 1_024));
68
+ const start = head.replace(/^\xef\xbb\xbf/, "").trimStart();
69
+ if (start.startsWith("%PDF-")) return "pdf";
70
+ if (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) {
71
+ const names = latin1(bytes.subarray(0, SNIFFED_HEAD)) + latin1(bytes.subarray(Math.max(SNIFFED_HEAD, bytes.length - SNIFFED_TAIL)));
72
+ if (names.includes("word/document.xml")) return "docx";
73
+ if (names.includes("ppt/presentation.xml") || names.includes("ppt/slides/")) return "pptx";
74
+ if (names.includes("xl/workbook.xml")) return "xlsx";
75
+ return undefined;
76
+ }
77
+ const tag = start.slice(0, 64).toLowerCase();
78
+ if (tag.startsWith("<!doctype html") || tag.startsWith("<html")) return "html";
79
+ return undefined;
80
+ }
81
+
82
+ /** Bytes as Latin-1 text, one character a byte: enough to find ASCII names in them. */
83
+ function latin1(bytes: Uint8Array): string {
84
+ let out = "";
85
+ for (let at = 0; at < bytes.length; at += 8_192) out += String.fromCharCode(...bytes.subarray(at, at + 8_192));
86
+ return out;
52
87
  }
53
88
 
54
89
  export type PdfExtractorOptions = {
package/src/library.ts CHANGED
@@ -7,7 +7,8 @@ import { EventEmitter, eventErrorOf, newRunId, type IngestEvent, type IngestStag
7
7
  import { detectFormat, extractText } from "./extract.js";
8
8
  import { Limiter } from "./limiter.js";
9
9
  import { TimeSlicer } from "./pause.js";
10
- import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline, type WholeRead } from "./plan.js";
10
+ import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline, TABLE_FORMATS, type WholeRead } from "./plan.js";
11
+ import { measureQuality, type TextQuality } from "./quality.js";
11
12
  import { openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
12
13
  import { numberLines, SearchableDocument, type DocumentSource } from "./search.js";
13
14
  import { DOCUMENT_ID_PATTERN } from "./stores.js";
@@ -655,6 +656,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
655
656
  let measured: Awaited<ReturnType<typeof measureText>>;
656
657
  let outline: DocumentMeta["outline"];
657
658
  let logProfile: DocumentMeta["logProfile"];
659
+ let quality: TextQuality = {};
658
660
  let index: Awaited<ReturnType<typeof buildTextIndexInSlices>> | undefined;
659
661
  try {
660
662
  signal.throwIfAborted();
@@ -694,6 +696,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
694
696
  if (measured.utf8 > maxTextBytes) throw tooMuchText(name, maxTextBytes);
695
697
  outline = await buildOutlineInSlices(lines, format, slicer);
696
698
  logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
699
+ quality = await measureQuality(lines, format, slicer);
697
700
  // The line index, so that the text can be read by range: a few bytes a line, built from the
698
701
  // UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
699
702
  // then loads whole, so that switching to reading by range finds it ready.
@@ -726,6 +729,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
726
729
  ...(keepOriginal ? { originalKept: true } : {}),
727
730
  outline,
728
731
  ...(logProfile ? { logProfile } : {}),
732
+ ...quality,
729
733
  createdAt: created.toISOString(),
730
734
  // Never, for a time to live without end (or one that runs past what a date can hold).
731
735
  expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
@@ -796,7 +800,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
796
800
  checkOwner(input.owner);
797
801
  const name = cleanFileName(input.name);
798
802
  const mimeType = input.mimeType?.trim() || "application/octet-stream";
799
- const format = detectFormat(name, mimeType);
803
+ // A file whose name and type say nothing is known by its bytes: a PDF, an Office file, a page.
804
+ const format = detectFormat(name, mimeType, input.bytes instanceof Uint8Array ? input.bytes : undefined);
800
805
  // Progress is worked out only for someone who listens.
801
806
  const progress = events.active ? new IngestProgress(events) : undefined;
802
807
  let meta: DocumentMeta;
@@ -911,6 +916,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
911
916
  ...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
912
917
  // `analyze_whole_document` is declared only when it can read at least one of the documents.
913
918
  wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
919
+ // `aggregate_table` only when one may hold a table.
920
+ tables: documents.some((meta) => TABLE_FORMATS.has(meta.format)),
914
921
  ...rest,
915
922
  });
916
923
  },
package/src/plan.ts CHANGED
@@ -1,5 +1,9 @@
1
+ import { pageList } from "./quality.js";
1
2
  import { plural, sliceWhole, wellFormed } from "./text.js";
2
- import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
3
+ import type { Budget, DocumentFormat, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
4
+
5
+ /** Formats whose documents may hold a table that `aggregate_table` reads. */
6
+ export const TABLE_FORMATS: ReadonlySet<DocumentFormat> = new Set<DocumentFormat>(["csv", "xlsx", "docx", "pptx", "pdf", "html", "markdown"]);
3
7
 
4
8
  /** Bytes kept free for document cards, the tool declarations, and JSON framing. */
5
9
  export const REQUEST_BYTES_MARGIN = 256 * 1024;
@@ -159,6 +163,7 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false, w
159
163
  HOW_TO_READ[wholeRead],
160
164
  ...(viewable ? ["Its text cannot show pictures. To see a picture, a chart or the layout of a page, look at the page with view_pages."] : []),
161
165
  ...(note ? [note] : []),
166
+ ...qualityLines(meta, viewable),
162
167
  ];
163
168
  const profile = meta.logProfile;
164
169
  if (profile) {
@@ -180,6 +185,16 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false, w
180
185
  return out.join("\n");
181
186
  }
182
187
 
188
+ /** What the card says of the quality of a document's text (see `measureQuality`). */
189
+ function qualityLines(meta: DocumentMeta, viewable: boolean): string[] {
190
+ const out: string[] = [];
191
+ const look = viewable ? " Look at them with view_pages." : "";
192
+ if (meta.pagesWithoutText?.length) out.push(`Pages without text (scans, photos or charts, whose content is not in the text): ${pageList(meta.pagesWithoutText)}.${look}`);
193
+ if (meta.garbledPages?.length) out.push(`Pages whose text looks garbled, not to be relied on: ${pageList(meta.garbledPages)}.${look}`);
194
+ if (meta.scripts?.length) out.push(`Written in: ${meta.scripts.map((share) => `${share.script} ${share.percent}%`).join(", ")}. Search in the language of the text.`);
195
+ return out;
196
+ }
197
+
183
198
  /**
184
199
  * The tool guide for the system prompt. `searchable` are the files the model reads through the
185
200
  * text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
@@ -199,6 +214,7 @@ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: D
199
214
  "- To count or list what can be matched as text (a word, an ID, an error code, a log level, a pattern), use search_document in exact or regex mode: its total_matching_lines is exact.",
200
215
  "- To count per group (per hour or day, per error code or ID with a regex group, per message shape), pass group_by: one call gives every count. For more matches than a result shows, search again from its next_from_line, or with order \"last\" for the last ones.",
201
216
  "- Search for the bare form of a word: a search matches inside longer words, so \"timeout\" also finds \"timeouts\", and a Hebrew word without its prefix letters (חוזה, not בחוזה) finds every form of it.",
217
+ ...(searchable.some((meta) => TABLE_FORMATS.has(meta.format)) ? ["- To add up, average, count or group the rows of a table (a CSV, an Excel sheet, a | cell | table), use aggregate_table: it reads every row, and its numbers are exact. Do not add numbers up from rows you read."] : []),
202
218
  "- read_document reads a line range. Read around search hits before you rely on them.",
203
219
  "- get_document_overview returns the outline, log profile, and the start and end of a file.",
204
220
  ...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of the file and cannot be done by matching text: a full summary, a timeline, or items that must be judged by meaning. It is slow and costly, and it can miss items of a long list."] : []),
package/src/quality.ts ADDED
@@ -0,0 +1,146 @@
1
+ import type { TimeSlicer } from "./pause.js";
2
+ import type { DocumentFormat, DocumentMeta } from "./types.js";
3
+
4
+ /**
5
+ * Signs of the quality of a document's text, worked out at ingest and shown on its card, so the
6
+ * model knows where the text cannot be trusted before it relies on it:
7
+ * - the pages of a PDF that have no text (a scan, a photo), and those whose text layer looks
8
+ * garbled (fonts without a Unicode map give "ÞÞÞ" or "�����");
9
+ * - the scripts the text is written in, when it is not Latin alone: a Hebrew file is searched in
10
+ * Hebrew.
11
+ */
12
+ export type TextQuality = Pick<DocumentMeta, "pagesWithoutText" | "garbledPages" | "scripts">;
13
+
14
+ /** Page numbers kept in a list, at most. */
15
+ const MAX_LISTED_PAGES = 200;
16
+ /** Characters of the text the script shares are counted over. */
17
+ const SCRIPT_SAMPLE = 2 * 1024 * 1024;
18
+ /** Letters needed before shares are given. */
19
+ const MIN_LETTERS = 200;
20
+ /** A script is named when it has at least this share of the letters, in percent. */
21
+ const MIN_SHARE = 5;
22
+ /** A page is judged garbled only with at least this many characters that are not white space. */
23
+ const MIN_PAGE_CHARACTERS = 40;
24
+
25
+ const PAGE_LINE = /^--- Page (\d+) ---$/;
26
+ const NO_TEXT_LINE = "[No text on this page. It may be a scan, a photo, or a chart.]";
27
+ const PICTURE_LINE = "[Picture on this page. This text cannot show it.]";
28
+
29
+ /**
30
+ * The script of the letter at `at`, or undefined when it is not a letter. The common scripts are
31
+ * known by their code points, with no regular expression; only rarer blocks are tested.
32
+ */
33
+ function letterScript(text: string, at: number): string | undefined {
34
+ const code = text.charCodeAt(at);
35
+ if (code < 0x80) return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) ? "Latin" : undefined;
36
+ if (code >= 0x5d0 && code <= 0x5f2) return code <= 0x5ea || code >= 0x5f0 ? "Hebrew" : undefined;
37
+ if (code >= 0x591 && code <= 0x5cf) return undefined; // Hebrew points and marks
38
+ if (code >= 0xc0 && code <= 0x24f) return code === 0xd7 || code === 0xf7 ? undefined : "Latin";
39
+ if ((code >= 0x620 && code <= 0x64a) || (code >= 0x671 && code <= 0x6d3)) return "Arabic";
40
+ if (code >= 0x410 && code <= 0x44f) return "Cyrillic";
41
+ if (code >= 0x4e00 && code <= 0x9fff) return "CJK";
42
+ if (code >= 0xdc00 && code <= 0xdfff) return undefined;
43
+ const character = code >= 0xd800 && code <= 0xdbff ? text.slice(at, at + 2) : text[at]!;
44
+ return LETTER.test(character) ? scriptOf(character.codePointAt(0)!) : undefined;
45
+ }
46
+
47
+ /** The script of a letter, by its code point. */
48
+ function scriptOf(code: number): string {
49
+ if (code < 0x250) return "Latin";
50
+ if (code >= 0x370 && code < 0x400) return "Greek";
51
+ if (code >= 0x400 && code < 0x530) return "Cyrillic";
52
+ if (code >= 0x590 && code < 0x600) return "Hebrew";
53
+ if ((code >= 0x600 && code < 0x780) || (code >= 0xfb50 && code < 0xfe00) || (code >= 0xfe70 && code < 0xff00)) return "Arabic";
54
+ if (code >= 0xfb1d && code < 0xfb50) return "Hebrew";
55
+ if (code >= 0x900 && code < 0x980) return "Devanagari";
56
+ if (code >= 0xe00 && code < 0xe80) return "Thai";
57
+ if ((code >= 0x3040 && code < 0x3100) || (code >= 0x3400 && code < 0xa000) || (code >= 0xac00 && code < 0xd7b0) || (code >= 0x1100 && code < 0x1200)) return "CJK";
58
+ if (code >= 0x1e00 && code < 0x1f00) return "Latin";
59
+ return "other";
60
+ }
61
+
62
+ const LETTER = /\p{L}/u;
63
+
64
+ /** The text quality of a document, from its lines (see `TextQuality`). */
65
+ export async function measureQuality(lines: string[], format: DocumentFormat, slicer: TimeSlicer): Promise<TextQuality> {
66
+ const empty: number[] = [];
67
+ const garbled: number[] = [];
68
+ let emptyCount = 0;
69
+ let garbledCount = 0;
70
+ // The page being read: its number, its characters that are not white space, its letters and
71
+ // digits, its replacement characters, and whether it said it has no text.
72
+ let page = 0;
73
+ let characters = 0;
74
+ let wordy = 0;
75
+ let replaced = 0;
76
+ let noText = false;
77
+ const endPage = () => {
78
+ if (page === 0) return;
79
+ if (noText && characters === 0) {
80
+ emptyCount++;
81
+ if (empty.length < MAX_LISTED_PAGES) empty.push(page);
82
+ } else if (characters >= MIN_PAGE_CHARACTERS && (wordy / characters < 0.3 || replaced > Math.max(6, characters * 0.03))) {
83
+ garbledCount++;
84
+ if (garbled.length < MAX_LISTED_PAGES) garbled.push(page);
85
+ }
86
+ };
87
+ const letters = new Map<string, number>();
88
+ let sampled = 0;
89
+ let total = 0;
90
+ /** Adds a line of a PDF page to its counts, a character code at a time. */
91
+ const countPage = (line: string) => {
92
+ for (let at = 0; at < line.length; at++) {
93
+ const code = line.charCodeAt(at);
94
+ if (code === 32 || code === 9 || code === 0xa0 || code === 0x202f) continue;
95
+ // The second half of a character outside the basic plane is counted with its first.
96
+ if (code >= 0xdc00 && code <= 0xdfff) continue;
97
+ characters++;
98
+ if (code === 0xfffd) replaced++;
99
+ else if ((code >= 48 && code <= 57) || letterScript(line, at) !== undefined) wordy++;
100
+ }
101
+ };
102
+ for (let index = 0; index < lines.length; index++) {
103
+ if ((index & 4095) === 4095) await slicer.maybePause();
104
+ const line = lines[index]!;
105
+ if (format === "pdf") {
106
+ const header = PAGE_LINE.exec(line);
107
+ if (header && Number(header[1]) === page + 1) {
108
+ endPage();
109
+ page++;
110
+ characters = wordy = replaced = 0;
111
+ noText = false;
112
+ continue;
113
+ }
114
+ if (line === NO_TEXT_LINE) {
115
+ noText = true;
116
+ continue;
117
+ }
118
+ if (line !== PICTURE_LINE) countPage(line);
119
+ }
120
+ if (sampled < SCRIPT_SAMPLE) {
121
+ sampled += line.length + 1;
122
+ for (let at = 0; at < line.length; at++) {
123
+ const script = letterScript(line, at);
124
+ if (script === undefined) continue;
125
+ letters.set(script, (letters.get(script) ?? 0) + 1);
126
+ total++;
127
+ }
128
+ }
129
+ }
130
+ endPage();
131
+ const shares = total >= MIN_LETTERS
132
+ ? [...letters].map(([script, count]) => ({ script, percent: Math.round((count / total) * 100) })).filter((share) => share.percent >= MIN_SHARE && share.script !== "other").sort((left, right) => right.percent - left.percent)
133
+ : [];
134
+ const notLatinOnly = shares.some((share) => share.script !== "Latin");
135
+ return {
136
+ ...(emptyCount > 0 ? { pagesWithoutText: empty } : {}),
137
+ ...(garbledCount > 0 ? { garbledPages: garbled } : {}),
138
+ ...(notLatinOnly ? { scripts: shares } : {}),
139
+ };
140
+ }
141
+
142
+ /** Page numbers as a short list: "3, 7, 12" or "3, 7, 12 and 40 more". */
143
+ export function pageList(pages: number[], shown = 12): string {
144
+ const listed = pages.slice(0, shown).join(", ");
145
+ return pages.length > shown ? `${listed} and ${pages.length - shown} more` : listed;
146
+ }