llm-large-files 0.1.0 → 0.2.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +1 -1
  3. package/dist/analyze.d.ts.map +1 -1
  4. package/dist/analyze.js +5 -1
  5. package/dist/analyze.js.map +1 -1
  6. package/dist/extract.d.ts +17 -1
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +73 -23
  9. package/dist/extract.js.map +1 -1
  10. package/dist/gemini/chat.d.ts +22 -2
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +41 -24
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts.map +1 -1
  15. package/dist/gemini/generate.js +4 -1
  16. package/dist/gemini/generate.js.map +1 -1
  17. package/dist/index.d.ts +2 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/library.d.ts +6 -0
  22. package/dist/library.d.ts.map +1 -1
  23. package/dist/library.js +15 -1
  24. package/dist/library.js.map +1 -1
  25. package/dist/map-reduce.d.ts +7 -0
  26. package/dist/map-reduce.d.ts.map +1 -1
  27. package/dist/map-reduce.js +58 -16
  28. package/dist/map-reduce.js.map +1 -1
  29. package/dist/pdf-layout.d.ts +32 -0
  30. package/dist/pdf-layout.d.ts.map +1 -0
  31. package/dist/pdf-layout.js +790 -0
  32. package/dist/pdf-layout.js.map +1 -0
  33. package/dist/plan.d.ts.map +1 -1
  34. package/dist/plan.js +6 -2
  35. package/dist/plan.js.map +1 -1
  36. package/dist/search.d.ts +8 -4
  37. package/dist/search.d.ts.map +1 -1
  38. package/dist/search.js +49 -24
  39. package/dist/search.js.map +1 -1
  40. package/dist/text.d.ts +18 -4
  41. package/dist/text.d.ts.map +1 -1
  42. package/dist/text.js +155 -15
  43. package/dist/text.js.map +1 -1
  44. package/dist/tools.d.ts.map +1 -1
  45. package/dist/tools.js +11 -3
  46. package/dist/tools.js.map +1 -1
  47. package/dist/types.d.ts +6 -0
  48. package/dist/types.d.ts.map +1 -1
  49. package/docs/api.md +20 -3
  50. package/docs/configuration.md +73 -5
  51. package/docs/getting-started.md +7 -4
  52. package/docs/how-it-works.md +26 -8
  53. package/docs/security.md +18 -5
  54. package/package.json +91 -91
  55. package/src/analyze.ts +3 -1
  56. package/src/extract.ts +77 -22
  57. package/src/gemini/chat.ts +60 -25
  58. package/src/gemini/generate.ts +3 -1
  59. package/src/index.ts +2 -1
  60. package/src/library.ts +241 -226
  61. package/src/map-reduce.ts +69 -16
  62. package/src/node/handlers.ts +122 -122
  63. package/src/pdf-layout.ts +771 -0
  64. package/src/plan.ts +100 -98
  65. package/src/search.ts +48 -25
  66. package/src/stores.ts +132 -132
  67. package/src/text.ts +131 -14
  68. package/src/tools.ts +274 -264
  69. package/src/types.ts +174 -168
package/src/library.ts CHANGED
@@ -1,226 +1,241 @@
1
- import { randomUUID } from "node:crypto";
2
- import { buildLogProfile, buildOutline, looksLikeLog } from "./analyze.js";
3
- import { detectFormat, extractText } from "./extract.js";
4
- import { documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
5
- import { SearchableDocument } from "./search.js";
6
- import { DOCUMENT_ID_PATTERN } from "./stores.js";
7
- import { estimateTokens, normalizeText, utf8Bytes, wrapLongLines } from "./text.js";
8
- import { createDocumentTools } from "./tools.js";
9
- import type {
10
- Budget,
11
- DocumentFormat,
12
- DocumentMeta,
13
- DocumentStore,
14
- DocumentSummary,
15
- Extractor,
16
- GenerateText,
17
- PreparedContext,
18
- ProgressListener,
19
- ToolSet,
20
- } from "./types.js";
21
-
22
- /** Defaults sized for a 1M-token model behind a 10 MB request limit. */
23
- export const DEFAULT_BUDGET: Budget = {
24
- contextTokens: 1_000_000,
25
- maxRequestBytes: 10_000_000,
26
- inlineTokens: 200_000,
27
- reservedTokens: 64_000,
28
- mapChunkTokens: 100_000,
29
- maxMapChunks: 30,
30
- toolResultCharacters: 24_000,
31
- };
32
-
33
- export type LargeFilesOptions = {
34
- /** Where extracted text is kept: `new FileDocumentStore(dir)`, `new MemoryDocumentStore()`, or your own. */
35
- store: DocumentStore;
36
- /** Your model's limits. Anything left out uses DEFAULT_BUDGET. */
37
- budget?: Partial<Budget>;
38
- /** How long uploaded documents are kept. Defaults to 72 hours. */
39
- ttlMs?: number;
40
- /** Largest accepted upload. Defaults to 100 MB. */
41
- maxUploadBytes?: number;
42
- /** Override or add text extractors per format. */
43
- extractors?: Partial<Record<DocumentFormat, Extractor>>;
44
- /** How many parsed documents to keep in memory for repeated tool calls. Defaults to 6. */
45
- cacheSize?: number;
46
- /** Clock override, for tests. */
47
- now?: () => Date;
48
- };
49
-
50
- export type IngestInput = {
51
- name: string;
52
- mimeType?: string;
53
- bytes: Uint8Array;
54
- /** The user (or tenant) the document belongs to. Later calls must pass the same owner. */
55
- owner?: string;
56
- };
57
-
58
- /** Access options. When a document has an owner, only that owner can use it. */
59
- export type AccessOptions = { owner?: string };
60
-
61
- export type ToolOptions = {
62
- /** Enables `analyze_whole_document`, which reads the entire file in parts. */
63
- generate?: GenerateText;
64
- /** Progress of whole-document reads, for status messages. */
65
- onProgress?: ProgressListener;
66
- signal?: AbortSignal;
67
- };
68
-
69
- export interface LargeFiles {
70
- /** The effective budget (defaults merged with your overrides). */
71
- readonly budget: Budget;
72
- readonly maxUploadBytes: number;
73
- /** Extracts, normalizes, profiles, and stores a file. Throws a user-readable Error on bad input. */
74
- ingest(input: IngestInput): Promise<DocumentMeta>;
75
- getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
76
- delete(id: string, access?: AccessOptions): Promise<boolean>;
77
- /** Removes expired documents from the store. Returns how many were removed. */
78
- sweep(): Promise<number>;
79
- /**
80
- * Plans one model request: which documents go in whole and which become searchable cards.
81
- * `base` is the size of everything else in the request (messages, system prompt, other files).
82
- */
83
- prepare(ids: string[], base: { tokens: number; bytes: number }, access?: AccessOptions): Promise<PreparedContext>;
84
- /** Tools scoped to these documents. Pass `generate` to enable whole-document analysis. */
85
- tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
86
- }
87
-
88
- export function isDocumentId(value: unknown): value is string {
89
- return typeof value === "string" && DOCUMENT_ID_PATTERN.test(value);
90
- }
91
-
92
- /** The fields of a document that are safe to return to a browser. */
93
- export function toDocumentSummary(meta: DocumentMeta): DocumentSummary {
94
- return {
95
- id: meta.id,
96
- name: meta.name,
97
- mimeType: meta.mimeType,
98
- format: meta.format,
99
- bytes: meta.bytes,
100
- lines: meta.lines,
101
- estimatedTokens: meta.estimatedTokens,
102
- ...(meta.pages ? { pages: meta.pages } : {}),
103
- expiresAt: meta.expiresAt,
104
- };
105
- }
106
-
107
- function allowed(meta: DocumentMeta, access: AccessOptions | undefined): boolean {
108
- return meta.owner === undefined || meta.owner === access?.owner;
109
- }
110
-
111
- export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
112
- const budget: Budget = { ...DEFAULT_BUDGET, ...options.budget };
113
- const ttlMs = options.ttlMs ?? 72 * 60 * 60 * 1000;
114
- const maxUploadBytes = options.maxUploadBytes ?? 100 * 1024 * 1024;
115
- const now = options.now ?? (() => new Date());
116
- const cacheSize = Math.max(1, options.cacheSize ?? 6);
117
- const cache = new Map<string, SearchableDocument>();
118
-
119
- async function load(id: string): Promise<SearchableDocument | undefined> {
120
- const cached = cache.get(id);
121
- if (cached) {
122
- if (Date.parse(cached.meta.expiresAt) > now().getTime()) {
123
- // Refresh its place as most recently used.
124
- cache.delete(id);
125
- cache.set(id, cached);
126
- return cached;
127
- }
128
- cache.delete(id);
129
- }
130
- const stored = await options.store.get(id);
131
- if (!stored) return undefined;
132
- const document = new SearchableDocument(stored);
133
- cache.set(id, document);
134
- while (cache.size > cacheSize) cache.delete(cache.keys().next().value!);
135
- return document;
136
- }
137
-
138
- async function metaFor(id: string, access: AccessOptions | undefined): Promise<DocumentMeta | undefined> {
139
- if (!isDocumentId(id)) return undefined;
140
- const meta = await options.store.getMeta(id);
141
- return meta && allowed(meta, access) ? meta : undefined;
142
- }
143
-
144
- return {
145
- budget,
146
- maxUploadBytes,
147
-
148
- async ingest(input) {
149
- const name = input.name.trim().split(/[\\/]/).at(-1)?.slice(0, 255) || "file";
150
- const mimeType = input.mimeType?.trim() || "application/octet-stream";
151
- if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
152
- if (input.bytes.byteLength > maxUploadBytes) {
153
- throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
154
- }
155
- let format = detectFormat(name, mimeType);
156
- const extracted = await extractText(input.bytes, { name, mimeType, format }, options.extractors);
157
- const { text, wrapped } = wrapLongLines(normalizeText(extracted.text));
158
- if (!text.trim()) throw new Error(`${name} did not contain any text.`);
159
- const lines = text.split("\n");
160
- if (text.endsWith("\n")) lines.pop();
161
- if (format === "text" && looksLikeLog(lines)) format = "log";
162
- const created = now();
163
- const meta: DocumentMeta = {
164
- id: `doc_${randomUUID().replaceAll("-", "")}`,
165
- ...(input.owner !== undefined ? { owner: input.owner } : {}),
166
- name,
167
- mimeType,
168
- format,
169
- bytes: input.bytes.byteLength,
170
- textBytes: utf8Bytes(text),
171
- characters: text.length,
172
- lines: lines.length,
173
- estimatedTokens: estimateTokens(text),
174
- wrappedLines: wrapped,
175
- ...(extracted.pages ? { pages: extracted.pages } : {}),
176
- outline: buildOutline(lines, format),
177
- ...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
178
- createdAt: created.toISOString(),
179
- expiresAt: new Date(created.getTime() + ttlMs).toISOString(),
180
- };
181
- await options.store.put({ meta, text });
182
- return meta;
183
- },
184
-
185
- getMeta: metaFor,
186
-
187
- async delete(id, access) {
188
- if (!await metaFor(id, access)) return false;
189
- cache.delete(id);
190
- return options.store.delete(id);
191
- },
192
-
193
- async sweep() {
194
- return options.store.sweep?.(now()) ?? 0;
195
- },
196
-
197
- async prepare(ids, base, access) {
198
- const unique = [...new Set(ids)];
199
- const documents: SearchableDocument[] = [];
200
- const missing: string[] = [];
201
- for (const id of unique) {
202
- const document = isDocumentId(id) ? await load(id) : undefined;
203
- // A document owned by someone else is reported as missing, not as forbidden.
204
- if (document && allowed(document.meta, access)) documents.push(document);
205
- else missing.push(id);
206
- }
207
- const plan = planDocuments(documents.map((document) => document.meta), budget, base);
208
- const inline = new Set(plan.inline.map((meta) => meta.id));
209
- const blocks = new Map<string, string>();
210
- for (const document of documents) {
211
- blocks.set(document.meta.id, inline.has(document.meta.id) ? renderInline(document) : renderCard(document));
212
- }
213
- return { plan, blocks, instruction: documentToolsInstruction(plan.searchable), missing };
214
- },
215
-
216
- tools(documents, toolOptions = {}) {
217
- return createDocumentTools({
218
- load,
219
- documentIds: documents.map((meta) => meta.id),
220
- names: Object.fromEntries(documents.map((meta) => [meta.id, meta.name])),
221
- budget,
222
- ...toolOptions,
223
- });
224
- },
225
- };
226
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import { buildLogProfile, buildOutline, looksLikeLog } from "./analyze.js";
3
+ import { detectFormat, extractText } from "./extract.js";
4
+ import { documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
5
+ import { SearchableDocument } from "./search.js";
6
+ import { DOCUMENT_ID_PATTERN } from "./stores.js";
7
+ import { estimateTokens, normalizeText, utf8Bytes, wrapLongLines } from "./text.js";
8
+ import { createDocumentTools } from "./tools.js";
9
+ import type {
10
+ Budget,
11
+ DocumentFormat,
12
+ DocumentMeta,
13
+ DocumentStore,
14
+ DocumentSummary,
15
+ Extractor,
16
+ GenerateText,
17
+ PreparedContext,
18
+ ProgressListener,
19
+ ToolSet,
20
+ } from "./types.js";
21
+
22
+ /** Defaults sized for a 1M-token model behind a 10 MB request limit. */
23
+ export const DEFAULT_BUDGET: Budget = {
24
+ contextTokens: 1_000_000,
25
+ maxRequestBytes: 10_000_000,
26
+ inlineTokens: 200_000,
27
+ reservedTokens: 64_000,
28
+ mapChunkTokens: 100_000,
29
+ maxMapChunks: 30,
30
+ toolResultCharacters: 24_000,
31
+ };
32
+
33
+ export type LargeFilesOptions = {
34
+ /** Where extracted text is kept: `new FileDocumentStore(dir)`, `new MemoryDocumentStore()`, or your own. */
35
+ store: DocumentStore;
36
+ /** Your model's limits. Anything left out uses DEFAULT_BUDGET. */
37
+ budget?: Partial<Budget>;
38
+ /** How long uploaded documents are kept. Defaults to 72 hours. */
39
+ ttlMs?: number;
40
+ /** Largest accepted upload. Defaults to 100 MB. */
41
+ maxUploadBytes?: number;
42
+ /** Override or add text extractors per format. */
43
+ extractors?: Partial<Record<DocumentFormat, Extractor>>;
44
+ /** How many parsed documents to keep in memory for repeated tool calls. Defaults to 6. */
45
+ cacheSize?: number;
46
+ /** Clock override, for tests. */
47
+ now?: () => Date;
48
+ };
49
+
50
+ export type IngestInput = {
51
+ name: string;
52
+ mimeType?: string;
53
+ bytes: Uint8Array;
54
+ /** The user (or tenant) the document belongs to. Later calls must pass the same owner. */
55
+ owner?: string;
56
+ };
57
+
58
+ /** Access options. When a document has an owner, only that owner can use it. */
59
+ export type AccessOptions = { owner?: string };
60
+
61
+ export type ToolOptions = {
62
+ /** Enables `analyze_whole_document`, which reads the entire file in parts. */
63
+ generate?: GenerateText;
64
+ /** Progress of whole-document reads, for status messages. */
65
+ onProgress?: ProgressListener;
66
+ signal?: AbortSignal;
67
+ };
68
+
69
+ export interface LargeFiles {
70
+ /** The effective budget (defaults merged with your overrides). */
71
+ readonly budget: Budget;
72
+ readonly maxUploadBytes: number;
73
+ /** Extracts, normalizes, profiles, and stores a file. Throws a user-readable Error on bad input. */
74
+ ingest(input: IngestInput): Promise<DocumentMeta>;
75
+ getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
76
+ delete(id: string, access?: AccessOptions): Promise<boolean>;
77
+ /** Removes expired documents from the store. Returns how many were removed. */
78
+ sweep(): Promise<number>;
79
+ /**
80
+ * Plans one model request: which documents go in whole and which become searchable cards.
81
+ * `base` is the size of everything else in the request (messages, system prompt, other files).
82
+ */
83
+ prepare(ids: string[], base: { tokens: number; bytes: number }, access?: AccessOptions): Promise<PreparedContext>;
84
+ /** Tools scoped to these documents. Pass `generate` to enable whole-document analysis. */
85
+ tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
86
+ }
87
+
88
+ export function isDocumentId(value: unknown): value is string {
89
+ return typeof value === "string" && DOCUMENT_ID_PATTERN.test(value);
90
+ }
91
+
92
+ /** The fields of a document that are safe to return to a browser. */
93
+ export function toDocumentSummary(meta: DocumentMeta): DocumentSummary {
94
+ return {
95
+ id: meta.id,
96
+ name: meta.name,
97
+ mimeType: meta.mimeType,
98
+ format: meta.format,
99
+ bytes: meta.bytes,
100
+ lines: meta.lines,
101
+ estimatedTokens: meta.estimatedTokens,
102
+ ...(meta.pages ? { pages: meta.pages } : {}),
103
+ expiresAt: meta.expiresAt,
104
+ };
105
+ }
106
+
107
+ /**
108
+ * A file name as one printable line: the last path segment, without control characters, line
109
+ * breaks, or text-direction overrides. Names are shown to the model and in UIs, so a name must
110
+ * not be able to start a new line of the prompt or disguise its extension.
111
+ */
112
+ export function cleanFileName(raw: string): string {
113
+ const base = raw.split(/[\\/]/).at(-1) ?? "";
114
+ return base
115
+ // Control characters, line and paragraph separators, and text-direction controls.
116
+ .replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ")
117
+ .replace(/\s+/g, " ")
118
+ .trim()
119
+ .slice(0, 255) || "file";
120
+ }
121
+
122
+ function allowed(meta: DocumentMeta, access: AccessOptions | undefined): boolean {
123
+ return meta.owner === undefined || meta.owner === access?.owner;
124
+ }
125
+
126
+ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
127
+ const budget: Budget = { ...DEFAULT_BUDGET, ...options.budget };
128
+ const ttlMs = options.ttlMs ?? 72 * 60 * 60 * 1000;
129
+ const maxUploadBytes = options.maxUploadBytes ?? 100 * 1024 * 1024;
130
+ const now = options.now ?? (() => new Date());
131
+ const cacheSize = Math.max(1, options.cacheSize ?? 6);
132
+ const cache = new Map<string, SearchableDocument>();
133
+
134
+ async function load(id: string): Promise<SearchableDocument | undefined> {
135
+ const cached = cache.get(id);
136
+ if (cached) {
137
+ if (Date.parse(cached.meta.expiresAt) > now().getTime()) {
138
+ // Refresh its place as most recently used.
139
+ cache.delete(id);
140
+ cache.set(id, cached);
141
+ return cached;
142
+ }
143
+ cache.delete(id);
144
+ }
145
+ const stored = await options.store.get(id);
146
+ if (!stored) return undefined;
147
+ const document = new SearchableDocument(stored);
148
+ cache.set(id, document);
149
+ while (cache.size > cacheSize) cache.delete(cache.keys().next().value!);
150
+ return document;
151
+ }
152
+
153
+ async function metaFor(id: string, access: AccessOptions | undefined): Promise<DocumentMeta | undefined> {
154
+ if (!isDocumentId(id)) return undefined;
155
+ const meta = await options.store.getMeta(id);
156
+ return meta && allowed(meta, access) ? meta : undefined;
157
+ }
158
+
159
+ return {
160
+ budget,
161
+ maxUploadBytes,
162
+
163
+ async ingest(input) {
164
+ const name = cleanFileName(input.name);
165
+ const mimeType = input.mimeType?.trim() || "application/octet-stream";
166
+ if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
167
+ if (input.bytes.byteLength > maxUploadBytes) {
168
+ throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
169
+ }
170
+ let format = detectFormat(name, mimeType);
171
+ const extracted = await extractText(input.bytes, { name, mimeType, format }, options.extractors);
172
+ const { text, wrapped } = wrapLongLines(normalizeText(extracted.text));
173
+ if (!text.trim()) throw new Error(`${name} did not contain any text.`);
174
+ const lines = text.split("\n");
175
+ if (text.endsWith("\n")) lines.pop();
176
+ if (format === "text" && looksLikeLog(lines)) format = "log";
177
+ const created = now();
178
+ const meta: DocumentMeta = {
179
+ id: `doc_${randomUUID().replaceAll("-", "")}`,
180
+ ...(input.owner !== undefined ? { owner: input.owner } : {}),
181
+ name,
182
+ mimeType,
183
+ format,
184
+ bytes: input.bytes.byteLength,
185
+ textBytes: utf8Bytes(text),
186
+ characters: text.length,
187
+ lines: lines.length,
188
+ estimatedTokens: estimateTokens(text),
189
+ wrappedLines: wrapped,
190
+ ...(extracted.pages ? { pages: extracted.pages } : {}),
191
+ outline: buildOutline(lines, format),
192
+ ...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
193
+ createdAt: created.toISOString(),
194
+ expiresAt: new Date(created.getTime() + ttlMs).toISOString(),
195
+ };
196
+ await options.store.put({ meta, text });
197
+ return meta;
198
+ },
199
+
200
+ getMeta: metaFor,
201
+
202
+ async delete(id, access) {
203
+ if (!await metaFor(id, access)) return false;
204
+ cache.delete(id);
205
+ return options.store.delete(id);
206
+ },
207
+
208
+ async sweep() {
209
+ return options.store.sweep?.(now()) ?? 0;
210
+ },
211
+
212
+ async prepare(ids, base, access) {
213
+ const unique = [...new Set(ids)];
214
+ const documents: SearchableDocument[] = [];
215
+ const missing: string[] = [];
216
+ for (const id of unique) {
217
+ const document = isDocumentId(id) ? await load(id) : undefined;
218
+ // A document owned by someone else is reported as missing, not as forbidden.
219
+ if (document && allowed(document.meta, access)) documents.push(document);
220
+ else missing.push(id);
221
+ }
222
+ const plan = planDocuments(documents.map((document) => document.meta), budget, base);
223
+ const inline = new Set(plan.inline.map((meta) => meta.id));
224
+ const blocks = new Map<string, string>();
225
+ for (const document of documents) {
226
+ blocks.set(document.meta.id, inline.has(document.meta.id) ? renderInline(document) : renderCard(document));
227
+ }
228
+ return { plan, blocks, instruction: documentToolsInstruction(plan.searchable), missing };
229
+ },
230
+
231
+ tools(documents, toolOptions = {}) {
232
+ return createDocumentTools({
233
+ load,
234
+ documentIds: documents.map((meta) => meta.id),
235
+ names: Object.fromEntries(documents.map((meta) => [meta.id, meta.name])),
236
+ budget,
237
+ ...toolOptions,
238
+ });
239
+ },
240
+ };
241
+ }
package/src/map-reduce.ts CHANGED
@@ -9,8 +9,15 @@ const FINAL_OUTPUT_TOKENS = 8_192;
9
9
  export type WholeDocumentResult = {
10
10
  answer: string;
11
11
  parts: number;
12
+ /** Parts that were read and had something relevant. Parts that could not be read are not counted. */
12
13
  relevantParts: number;
13
14
  failedParts: number;
15
+ /** Parts whose notes stopped at the output limit, so some of what they contain is missing. */
16
+ truncatedParts: number;
17
+ /** Note-merging steps that stopped at the output limit. */
18
+ truncatedMerges: number;
19
+ /** The final answer stopped at the output limit. */
20
+ answerTruncated: boolean;
14
21
  };
15
22
 
16
23
  /** Splits a document into line ranges that each fit one model request. */
@@ -62,6 +69,20 @@ async function withRetry(call: () => Promise<string>, signal?: AbortSignal): Pro
62
69
  }
63
70
  }
64
71
 
72
+ /** One model call, retried once. `truncated` is true when the reply that was kept hit the output limit. */
73
+ async function ask(
74
+ generate: GenerateText,
75
+ request: { system: string; prompt: string; maxOutputTokens: number },
76
+ signal: AbortSignal | undefined,
77
+ ): Promise<{ text: string; truncated: boolean }> {
78
+ let truncated = false;
79
+ const text = await withRetry(() => {
80
+ truncated = false;
81
+ return generate({ ...request, signal, onTruncated: () => { truncated = true; } });
82
+ }, signal);
83
+ return { text: text.trim(), truncated };
84
+ }
85
+
65
86
  /**
66
87
  * Answers a task that needs the whole document: each part is read separately ("map"),
67
88
  * then the notes are combined ("reduce"), in several rounds if the notes are still too large.
@@ -84,11 +105,14 @@ export async function analyzeWholeDocument(options: {
84
105
 
85
106
  let done = 0;
86
107
  let failed = 0;
108
+ let firstFailure = "";
109
+ let truncatedParts = 0;
87
110
  const notes = await pool(parts.length, options.concurrency ?? 4, async (index) => {
88
111
  const { from, to } = parts[index]!;
89
112
  let text: string;
113
+ let read = true;
90
114
  try {
91
- text = (await withRetry(() => generate({
115
+ const reply = await ask(generate, {
92
116
  system: "You read one part of a larger document and take notes for a later step that combines the notes from every part.",
93
117
  prompt: [
94
118
  `Task: ${task}`,
@@ -101,25 +125,45 @@ export async function analyzeWholeDocument(options: {
101
125
  "</part>",
102
126
  ].join("\n"),
103
127
  maxOutputTokens: PART_OUTPUT_TOKENS,
104
- signal,
105
- }), signal)).trim();
128
+ }, signal);
129
+ text = reply.text;
130
+ if (reply.truncated) {
131
+ truncatedParts++;
132
+ text += "\n[These notes were cut off at the output limit. This part has more relevant content than is listed here.]";
133
+ }
106
134
  } catch (error) {
107
135
  if (signal?.aborted) throw error;
108
136
  failed++;
109
- text = `[This part could not be read: ${error instanceof Error ? error.message : String(error)}]`;
137
+ read = false;
138
+ const reason = error instanceof Error ? error.message : String(error);
139
+ firstFailure ||= reason;
140
+ text = `[This part could not be read: ${reason}]`;
110
141
  }
111
142
  done++;
112
143
  onProgress?.({ kind: "map", message: `Reading ${name}: part ${done} of ${parts.length}`, done, total: parts.length });
113
- return { from, to, text };
144
+ return { from, to, text, read };
114
145
  }, signal);
115
146
 
147
+ // Nothing was read at all: an answer written from here would be invented.
148
+ if (failed === parts.length) throw new Error(`Could not read any part of ${name}: ${firstFailure}`);
149
+
116
150
  const relevant = notes.filter((note) => !note.text.toUpperCase().startsWith(NOTHING));
117
- if (relevant.length === 0) {
118
- return { answer: `No part of ${name} contained anything relevant to: ${task}`, parts: parts.length, relevantParts: 0, failedParts: failed };
151
+ const relevantParts = relevant.filter((note) => note.read).length;
152
+ if (relevantParts === 0) {
153
+ return {
154
+ answer: `No part of ${name} contained anything relevant to: ${task}${failed ? ` (${failed} of ${parts.length} parts could not be read.)` : ""}`,
155
+ parts: parts.length,
156
+ relevantParts: 0,
157
+ failedParts: failed,
158
+ truncatedParts,
159
+ truncatedMerges: 0,
160
+ answerTruncated: false,
161
+ };
119
162
  }
120
163
 
121
164
  let layer = relevant.map((note) => `### Lines ${note.from}-${note.to}\n${note.text}`);
122
165
  let round = 0;
166
+ let truncatedMerges = 0;
123
167
  // Combine notes in batches until one batch holds them all. Each merge is capped at
124
168
  // PART_OUTPUT_TOKENS, so the layer shrinks every round; the round cap is a safety net.
125
169
  while (layer.length > 1 && estimateTokens(layer.join("\n\n")) > budget.mapChunkTokens && round < 8) {
@@ -145,31 +189,40 @@ export async function analyzeWholeDocument(options: {
145
189
  }
146
190
  let combined = 0;
147
191
  layer = await pool(batches.length, options.concurrency ?? 4, async (index) => {
148
- const text = await withRetry(() => generate({
192
+ const reply = await ask(generate, {
149
193
  system: "You merge partial notes about a document into shorter notes, keeping every relevant fact and line citation.",
150
194
  prompt: `Task: ${task}\n\nMerge these notes from ${name} into one set of notes. Keep line citations.\n\n${batches[index]!.join("\n\n")}`,
151
195
  maxOutputTokens: PART_OUTPUT_TOKENS,
152
- signal,
153
- }), signal);
196
+ }, signal);
197
+ if (reply.truncated) truncatedMerges++;
154
198
  combined++;
155
199
  onProgress?.({ kind: "reduce", message: `Combining notes on ${name} (round ${round}): ${combined} of ${batches.length}`, done: combined, total: batches.length });
156
- return text.trim();
200
+ return reply.truncated ? `${reply.text}\n[These merged notes were cut off at the output limit.]` : reply.text;
157
201
  }, signal);
158
202
  }
159
203
 
160
- onProgress?.({ kind: "reduce", message: `Writing the answer from ${relevant.length} relevant parts of ${name}`, done: 0, total: 1 });
161
- const answer = await withRetry(() => generate({
204
+ onProgress?.({ kind: "reduce", message: `Writing the answer from ${relevantParts} relevant parts of ${name}`, done: 0, total: 1 });
205
+ const cutShort = truncatedParts + truncatedMerges;
206
+ const final = await ask(generate, {
162
207
  system: "You write a complete answer from notes taken across every part of a document.",
163
208
  prompt: [
164
209
  `Task: ${task}`,
165
210
  "",
166
211
  `These notes cover all ${parts.length} parts of ${name}${failed ? ` (${failed} part(s) could not be read)` : ""}. Parts with nothing relevant are omitted.`,
212
+ ...(cutShort ? [`Some notes were cut off at the output limit (they say so), so the notes are incomplete. Say in the answer that it is incomplete.`] : []),
167
213
  "Write one complete answer to the task from them. Keep line citations. Point out contradictions or gaps.",
168
214
  "",
169
215
  layer.join("\n\n"),
170
216
  ].join("\n"),
171
217
  maxOutputTokens: FINAL_OUTPUT_TOKENS,
172
- signal,
173
- }), signal);
174
- return { answer: answer.trim(), parts: parts.length, relevantParts: relevant.length, failedParts: failed };
218
+ }, signal);
219
+ return {
220
+ answer: final.text,
221
+ parts: parts.length,
222
+ relevantParts,
223
+ failedParts: failed,
224
+ truncatedParts,
225
+ truncatedMerges,
226
+ answerTruncated: final.truncated,
227
+ };
175
228
  }