llm-large-files 0.4.0 → 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.
Files changed (80) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist/cache.d.ts +11 -2
  3. package/dist/cache.d.ts.map +1 -1
  4. package/dist/cache.js +36 -7
  5. package/dist/cache.js.map +1 -1
  6. package/dist/errors.d.ts +21 -0
  7. package/dist/errors.d.ts.map +1 -0
  8. package/dist/errors.js +44 -0
  9. package/dist/errors.js.map +1 -0
  10. package/dist/gemini/chat.d.ts +5 -0
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +17 -1
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts +10 -0
  15. package/dist/gemini/generate.d.ts.map +1 -1
  16. package/dist/gemini/generate.js +110 -25
  17. package/dist/gemini/generate.js.map +1 -1
  18. package/dist/gemini/index.d.ts +1 -1
  19. package/dist/gemini/index.d.ts.map +1 -1
  20. package/dist/gemini/index.js +1 -1
  21. package/dist/gemini/index.js.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/library.d.ts +21 -2
  27. package/dist/library.d.ts.map +1 -1
  28. package/dist/library.js +46 -14
  29. package/dist/library.js.map +1 -1
  30. package/dist/map-reduce.d.ts +6 -0
  31. package/dist/map-reduce.d.ts.map +1 -1
  32. package/dist/map-reduce.js +34 -9
  33. package/dist/map-reduce.js.map +1 -1
  34. package/dist/plan.d.ts +20 -4
  35. package/dist/plan.d.ts.map +1 -1
  36. package/dist/plan.js +44 -7
  37. package/dist/plan.js.map +1 -1
  38. package/dist/ranged.d.ts +2 -2
  39. package/dist/ranged.d.ts.map +1 -1
  40. package/dist/ranged.js +11 -4
  41. package/dist/ranged.js.map +1 -1
  42. package/dist/search.d.ts +16 -2
  43. package/dist/search.d.ts.map +1 -1
  44. package/dist/search.js +109 -26
  45. package/dist/search.js.map +1 -1
  46. package/dist/stores.d.ts +5 -1
  47. package/dist/stores.d.ts.map +1 -1
  48. package/dist/stores.js +58 -15
  49. package/dist/stores.js.map +1 -1
  50. package/dist/text.d.ts +12 -1
  51. package/dist/text.d.ts.map +1 -1
  52. package/dist/text.js +43 -15
  53. package/dist/text.js.map +1 -1
  54. package/dist/tools.d.ts +12 -0
  55. package/dist/tools.d.ts.map +1 -1
  56. package/dist/tools.js +37 -11
  57. package/dist/tools.js.map +1 -1
  58. package/dist/types.d.ts +5 -0
  59. package/dist/types.d.ts.map +1 -1
  60. package/docs/api.md +13 -6
  61. package/docs/configuration.md +6 -1
  62. package/docs/getting-started.md +2 -0
  63. package/docs/how-it-works.md +8 -2
  64. package/docs/security.md +18 -3
  65. package/package.json +1 -1
  66. package/src/cache.ts +32 -8
  67. package/src/errors.ts +42 -0
  68. package/src/gemini/chat.ts +22 -1
  69. package/src/gemini/generate.ts +107 -25
  70. package/src/gemini/index.ts +1 -1
  71. package/src/index.ts +3 -2
  72. package/src/library.ts +63 -16
  73. package/src/map-reduce.ts +31 -8
  74. package/src/plan.ts +46 -7
  75. package/src/ranged.ts +13 -6
  76. package/src/search.ts +116 -25
  77. package/src/stores.ts +51 -15
  78. package/src/text.ts +39 -12
  79. package/src/tools.ts +43 -11
  80. package/src/types.ts +5 -0
@@ -73,9 +73,36 @@ export function geminiFunctionResponseTurns(calls: GeminiToolAnswer[], options:
73
73
  return [{ role: "user", parts: responses }, ...(files.length > 0 ? [{ role: "user" as const, parts: files }] : [])];
74
74
  }
75
75
 
76
+ /**
77
+ * A model that thinks counts its thoughts in `maxOutputTokens`. Asked for 4,096 tokens of notes on
78
+ * a part of a log, Gemini 3.8 Flash spent 3,931 of them thinking and wrote two lines, and Gemini 4
79
+ * wrote nothing at all (November 2026). A reply that was cut off that way is asked for again with
80
+ * this limit, the least Google recommends for a Gemini 4 model.
81
+ */
82
+ export const THINKING_OUTPUT_TOKENS = 32_768;
83
+
84
+ /**
85
+ * What has been learned about the model behind a URL, so that a whole-file read does not pay for
86
+ * the wasted request with every part: the output limit it needs, or 0 when it refused that limit.
87
+ */
88
+ const learnedLimits = new Map<string, number>();
89
+ /** The first request to a URL that is still on its way. Others wait for what it learns. */
90
+ const firstRequests = new Map<string, Promise<void>>();
91
+ /** URLs that have answered at least once. */
92
+ const answered = new Set<string>();
93
+ const MOST_REMEMBERED = 200;
94
+
95
+ function remember(url: string, limit: number): void {
96
+ if (learnedLimits.size >= MOST_REMEMBERED && !learnedLimits.has(url)) learnedLimits.clear();
97
+ learnedLimits.set(url, limit);
98
+ }
99
+
76
100
  /**
77
101
  * A `GenerateText` backed by a non-streaming `:generateContent` endpoint.
78
102
  * `generationConfig` lets the caller apply model-specific rules (thinking level, output floors).
103
+ *
104
+ * When a reply stops at the output limit with most of that limit spent on thoughts, the request
105
+ * is sent once more with `THINKING_OUTPUT_TOKENS`, and later requests to the same URL start there.
79
106
  */
80
107
  export function createGeminiGenerateText(options: {
81
108
  url: string;
@@ -85,31 +112,86 @@ export function createGeminiGenerateText(options: {
85
112
  timeoutMs?: number;
86
113
  }): GenerateText {
87
114
  const fetchImpl = options.fetchImpl ?? fetch;
115
+ const { url } = options;
88
116
  return async ({ system, prompt, maxOutputTokens, signal, onTruncated }) => {
89
- const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
90
- const response = await fetchImpl(options.url, {
91
- method: "POST",
92
- headers: options.headers,
93
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
94
- body: JSON.stringify({
95
- contents: [{ role: "user", parts: [{ text: prompt }] }],
96
- systemInstruction: { role: "system", parts: [{ text: system }] },
97
- generationConfig: options.generationConfig?.(maxOutputTokens) ?? { maxOutputTokens, temperature: 0.2 },
98
- }),
99
- });
100
- const data = await response.json().catch(() => null) as {
101
- error?: { message?: string };
102
- candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
103
- } | null;
104
- if (!response.ok) throw new Error(data?.error?.message ?? `The model returned HTTP ${response.status}.`);
105
- const candidate = data?.candidates?.[0];
106
- const text = (candidate?.content?.parts ?? [])
107
- .filter((part) => part.thought !== true && typeof part.text === "string")
108
- .map((part) => part.text as string)
109
- .join("");
110
- if (!text.trim()) throw new Error(`The model returned no text${candidate?.finishReason ? ` (${candidate.finishReason})` : ""}.`);
111
- // The text stops mid-list when the output limit is reached. Say so instead of passing it off as complete.
112
- if (candidate?.finishReason === "MAX_TOKENS") onTruncated?.();
113
- return text;
117
+ /** One request with an output limit: the text of the reply, why it ended, and what it thought. */
118
+ const send = async (limit: number): Promise<{ text: string; finishReason?: string; thoughts: number }> => {
119
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
120
+ const response = await fetchImpl(url, {
121
+ method: "POST",
122
+ headers: options.headers,
123
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
124
+ body: JSON.stringify({
125
+ contents: [{ role: "user", parts: [{ text: prompt }] }],
126
+ systemInstruction: { role: "system", parts: [{ text: system }] },
127
+ generationConfig: options.generationConfig?.(limit) ?? { maxOutputTokens: limit, temperature: 0.2 },
128
+ }),
129
+ });
130
+ const data = await response.json().catch(() => null) as {
131
+ error?: { message?: string };
132
+ candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
133
+ usageMetadata?: { thoughtsTokenCount?: unknown };
134
+ } | null;
135
+ if (!response.ok) throw Object.assign(new Error(data?.error?.message ?? `The model returned HTTP ${response.status}.`), { status: response.status });
136
+ const candidate = data?.candidates?.[0];
137
+ const text = (candidate?.content?.parts ?? [])
138
+ .filter((part) => part.thought !== true && typeof part.text === "string")
139
+ .map((part) => part.text as string)
140
+ .join("");
141
+ const thoughts = data?.usageMetadata?.thoughtsTokenCount;
142
+ return {
143
+ text,
144
+ ...(candidate?.finishReason ? { finishReason: candidate.finishReason } : {}),
145
+ thoughts: typeof thoughts === "number" ? thoughts : 0,
146
+ };
147
+ };
148
+
149
+ // The first request to a model finds out whether it thinks its limit away. The parts of a
150
+ // whole-file read are sent four at a time: the others wait for it, and one request is wasted
151
+ // on such a model, not four.
152
+ let learned = () => undefined as void;
153
+ if (!answered.has(url)) {
154
+ const first = firstRequests.get(url);
155
+ if (first) {
156
+ await first;
157
+ signal?.throwIfAborted();
158
+ } else {
159
+ firstRequests.set(url, new Promise<void>((resolve) => {
160
+ learned = () => {
161
+ if (answered.size >= MOST_REMEMBERED) answered.clear();
162
+ answered.add(url);
163
+ firstRequests.delete(url);
164
+ resolve();
165
+ };
166
+ }));
167
+ }
168
+ }
169
+ try {
170
+ const known = learnedLimits.get(url);
171
+ const limit = Math.max(maxOutputTokens, known ?? 0);
172
+ let reply = await send(limit);
173
+ // Cut off, with nothing written or with at least half of the limit gone on thoughts: the
174
+ // limit was too low for this model, not the notes too long.
175
+ const starved = reply.finishReason === "MAX_TOKENS" && (!reply.text.trim() || reply.thoughts >= limit / 2);
176
+ if (starved && known !== 0 && limit < THINKING_OUTPUT_TOKENS) {
177
+ remember(url, THINKING_OUTPUT_TOKENS);
178
+ try {
179
+ reply = await send(THINKING_OUTPUT_TOKENS);
180
+ } catch (error) {
181
+ if (signal?.aborted) throw error;
182
+ // A model or a gateway that refuses the larger limit (HTTP 400) is not asked for it again.
183
+ // Any other failure says nothing about the limit: the next request starts with it. What
184
+ // the first reply had is kept; with nothing in it, this error is the one to report.
185
+ if ((error as { status?: unknown } | null)?.status === 400) remember(url, 0);
186
+ if (!reply.text.trim()) throw error;
187
+ }
188
+ }
189
+ if (!reply.text.trim()) throw new Error(`The model returned no text${reply.finishReason ? ` (${reply.finishReason})` : ""}.`);
190
+ // The text stops mid-list when the output limit is reached. Say so instead of passing it off as complete.
191
+ if (reply.finishReason === "MAX_TOKENS") onTruncated?.();
192
+ return reply.text;
193
+ } finally {
194
+ learned();
195
+ }
114
196
  };
115
197
  }
@@ -2,6 +2,6 @@ export { askGemini, DocumentsNotFoundError, EXPLORER_INSTRUCTION, FINAL_ANSWER_A
2
2
  export type { AskGeminiOptions, AskGeminiResult, ChatTurn, GeminiContent, GeminiPart } from "./chat.js";
3
3
  export { geminiApi, vertexAi, vertexHost } from "./endpoints.js";
4
4
  export type { GeminiEndpoint } from "./endpoints.js";
5
- export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, toGeminiTools } from "./generate.js";
5
+ export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, THINKING_OUTPUT_TOKENS, toGeminiTools } from "./generate.js";
6
6
  export type { GeminiFunctionCall, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
7
7
  export { parseSseJson } from "./sse.js";
package/src/index.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  // Core: provider-neutral. Gemini helpers live in "llm-large-files/gemini",
2
2
  // Node HTTP handlers in "llm-large-files/node".
3
- export { createLargeFiles, DEFAULT_BUDGET, DEFAULT_CACHE_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, toDocumentSummary } from "./library.js";
3
+ export { createLargeFiles, DEFAULT_BUDGET, DEFAULT_CACHE_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, NEVER_EXPIRES, toDocumentSummary } from "./library.js";
4
4
  export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, PrepareOptions, ToolOptions } from "./library.js";
5
+ export { DocumentStoreError } from "./errors.js";
5
6
  export { FileDocumentStore, MemoryDocumentStore, DOCUMENT_ID_PATTERN } from "./stores.js";
6
7
  export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
7
8
  export type { PdfExtractorOptions } from "./extract.js";
8
9
  export { estimateTokens, utf8Bytes, jsonBytes } from "./text.js";
9
- export { MAX_VIEW_PAGES, TOOL_NAMES, toolResultSummary } from "./tools.js";
10
+ export { MAX_VIEW_PAGES, REGEX_BUDGET_MS, TOOL_NAMES, toolResultSummary } from "./tools.js";
10
11
  export type * from "./types.js";
package/src/library.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { buildLogProfile, buildOutline, looksLikeLog } from "./analyze.js";
3
3
  import { DocumentCache, documentVersion, type Sized } from "./cache.js";
4
+ import { DocumentStoreError } from "./errors.js";
4
5
  import { detectFormat, extractText } from "./extract.js";
5
6
  import { Limiter } from "./limiter.js";
6
- import { CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
7
+ import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
7
8
  import { openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
8
9
  import { numberLines, SearchableDocument, type DocumentSource } from "./search.js";
9
10
  import { DOCUMENT_ID_PATTERN } from "./stores.js";
10
11
  import { buildTextIndex, canSerialize, serializeTextIndex } from "./text-index.js";
11
- import { estimateTokens, normalizeText, utf8Bytes, wrapLongLines } from "./text.js";
12
+ import { estimateTokens, normalizeText, textSizes, wrapLongLines } from "./text.js";
12
13
  import { createDocumentTools } from "./tools.js";
13
14
  import type {
14
15
  Budget,
@@ -39,7 +40,10 @@ export type LargeFilesOptions = {
39
40
  store: DocumentStore;
40
41
  /** Your model's limits. Anything left out uses DEFAULT_BUDGET. */
41
42
  budget?: Partial<Budget>;
42
- /** How long uploaded documents are kept. Defaults to 72 hours. */
43
+ /**
44
+ * How long uploaded documents are kept. Defaults to 72 hours. `Infinity` keeps them until they
45
+ * are deleted: their `expiresAt` is then `NEVER_EXPIRES`.
46
+ */
43
47
  ttlMs?: number;
44
48
  /** Largest accepted upload. Defaults to 100 MB. */
45
49
  maxUploadBytes?: number;
@@ -65,7 +69,11 @@ export type LargeFilesOptions = {
65
69
  * deleted or expired on another server sharing the store is never served from memory here.
66
70
  */
67
71
  cacheBytes?: number;
68
- /** Also caps the number of documents kept (the only limit before 0.4). Unset: no cap on the number. */
72
+ /**
73
+ * Also caps the number of documents kept (the only limit before 0.4). Unset: no cap on the
74
+ * number. The pieces kept of a document that is read by range are not counted, and go when
75
+ * their document does.
76
+ */
69
77
  cacheSize?: number;
70
78
  /**
71
79
  * Documents whose text is at most this many bytes are loaded whole into memory (and kept there
@@ -112,6 +120,13 @@ export type ToolOptions = {
112
120
  /** Progress of whole-document reads, for status messages. */
113
121
  onProgress?: ProgressListener;
114
122
  signal?: AbortSignal;
123
+ /**
124
+ * The most time, in milliseconds, that the regex searches of this tool set may take together.
125
+ * Past it, a regex search answers with an error that tells the model to search another way.
126
+ * Defaults to 6,000. One search still stops after 3,000, and at once at a line its pattern
127
+ * cannot get past.
128
+ */
129
+ regexBudgetMs?: number;
115
130
  /**
116
131
  * Offers `view_pages`, which hands the model real pages of a PDF whose original file is kept
117
132
  * (see `keepOriginals`). The pages come back as a file, so turn this on only when your loop
@@ -177,6 +192,24 @@ export function cleanFileName(raw: string): string {
177
192
  .slice(0, 255) || "file";
178
193
  }
179
194
 
195
+ /**
196
+ * A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
197
+ * could not be read is not a document that is gone, and its own error names paths or hosts.
198
+ */
199
+ async function reading<T>(read: () => Promise<T>): Promise<T> {
200
+ try {
201
+ return await read();
202
+ } catch (error) {
203
+ throw error instanceof DocumentStoreError ? error : new DocumentStoreError(error);
204
+ }
205
+ }
206
+
207
+ /**
208
+ * The `expiresAt` of a document that never expires (`ttlMs: Infinity`): the last instant of the
209
+ * year 9999. A date, so that every comparison, and a server of an older version, reads it as any other.
210
+ */
211
+ export const NEVER_EXPIRES = "9999-12-31T23:59:59.999Z";
212
+
180
213
  function allowed(meta: DocumentMeta, access: AccessOptions | undefined): boolean {
181
214
  return meta.owner === undefined || meta.owner === access?.owner;
182
215
  }
@@ -206,7 +239,13 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
206
239
  /** Documents being opened, so that calls arriving together open each one once. */
207
240
  const opening = new Map<string, Promise<DocumentSource | undefined>>();
208
241
  /** The store, when large documents can be read from it by range rather than loaded whole. */
209
- const ranged = typeof store.readTextRange === "function" ? store as RangeStore : undefined;
242
+ const ranged: RangeStore | undefined = typeof store.readTextRange === "function" ? {
243
+ readTextRange: (id, start, end) => reading(() => store.readTextRange!(id, start, end)),
244
+ ...(store.getIndex ? { getIndex: (id: string) => reading(() => store.getIndex!(id)) } : {}),
245
+ ...(store.putIndex ? { putIndex: (id: string, index: Uint8Array) => store.putIndex!(id, index) } : {}),
246
+ } : undefined;
247
+ /** The uploaded file of a document, when the store keeps such files. */
248
+ const loadOriginal = store.getOriginal ? (id: string) => reading(() => store.getOriginal!(id)) : undefined;
210
249
  const wholeDocumentBytes = Math.max(0, options.wholeDocumentBytes ?? DEFAULT_WHOLE_DOCUMENT_BYTES);
211
250
  /** Documents whose saved index did not match their text: the next opening builds it from the text. */
212
251
  const rebuildIndex = new Set<string>();
@@ -219,7 +258,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
219
258
  },
220
259
  pieces: {
221
260
  get: (key, version) => cache.get(key, version) as CachedPiece | undefined,
222
- set: (key, version, piece) => cache.set(key, version, piece),
261
+ // A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with it.
262
+ set: (key, version, piece) => cache.set(key, version, piece, key.slice(0, key.indexOf("#"))),
223
263
  // A quarter of the cache: a few documents can be kept, and no one pushes out all the rest.
224
264
  maxDocumentBytes: cacheBytes / 4,
225
265
  },
@@ -235,7 +275,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
235
275
  */
236
276
  async function currentMeta(id: string): Promise<DocumentMeta | undefined> {
237
277
  if (!isDocumentId(id)) return undefined;
238
- const meta = await options.store.getMeta(id);
278
+ const meta = await reading(() => store.getMeta(id));
239
279
  if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
240
280
  forget(id);
241
281
  return undefined;
@@ -271,7 +311,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
271
311
  const rebuild = rebuildIndex.delete(id);
272
312
  return openRangedDocument(ranged, meta, scan, { ignoreSavedIndex: rebuild });
273
313
  }
274
- const stored = await store.get(id);
314
+ const stored = await reading(() => store.get(id));
275
315
  return stored ? new SearchableDocument(stored) : undefined;
276
316
  }
277
317
 
@@ -279,14 +319,14 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
279
319
  * What a document contributes to the prompt: its text, or its card. Undefined when it is gone
280
320
  * by now. A copy found to disagree with the store is opened again once.
281
321
  */
282
- async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean): Promise<string | undefined> {
322
+ async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean, readableWhole: boolean): Promise<string | undefined> {
283
323
  for (let attempt = 0; attempt < 2; attempt++) {
284
324
  const document = await load(id, attempt === 0 ? meta : undefined);
285
325
  if (!document) return undefined;
286
326
  try {
287
327
  return whole
288
328
  ? renderInline(document.meta, await document.readText())
289
- : renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable);
329
+ : renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, readableWhole);
290
330
  } catch (error) {
291
331
  if (!document.broken) {
292
332
  // Deleted between the look-up and the read: the same as missing.
@@ -328,6 +368,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
328
368
  if (text.endsWith("\n")) lines.pop();
329
369
  if (format === "text" && looksLikeLog(lines)) format = "log";
330
370
  const created = now();
371
+ const expires = created.getTime() + ttlMs;
372
+ const sizes = textSizes(text);
331
373
  const keepOriginal = keeps(format);
332
374
  const meta: DocumentMeta = {
333
375
  id: `doc_${randomUUID().replaceAll("-", "")}`,
@@ -336,7 +378,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
336
378
  mimeType,
337
379
  format,
338
380
  bytes: input.bytes.byteLength,
339
- textBytes: utf8Bytes(text),
381
+ textBytes: sizes.utf8,
382
+ jsonBytes: sizes.json,
340
383
  characters: text.length,
341
384
  lines: lines.length,
342
385
  estimatedTokens: estimateTokens(text),
@@ -346,7 +389,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
346
389
  outline: buildOutline(lines, format),
347
390
  ...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
348
391
  createdAt: created.toISOString(),
349
- expiresAt: new Date(created.getTime() + ttlMs).toISOString(),
392
+ // Never, for a time to live without end (or one that runs past what a date can hold).
393
+ expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
350
394
  };
351
395
  // The line index, so that the text can be read by range: a few bytes a line, built from the
352
396
  // UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
@@ -373,7 +417,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
373
417
 
374
418
  async getOriginal(id, access) {
375
419
  const meta = await metaFor(id, access);
376
- return meta?.originalKept ? options.store.getOriginal?.(id) : undefined;
420
+ return meta?.originalKept ? loadOriginal?.(id) : undefined;
377
421
  },
378
422
 
379
423
  async delete(id, access) {
@@ -410,12 +454,14 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
410
454
  const blocks = new Map<string, string>();
411
455
  const gone: string[] = [];
412
456
  for (const meta of documents) {
413
- const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id));
457
+ const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), canBeReadWhole(meta, budget));
414
458
  if (text === undefined) gone.push(meta.id);
415
459
  else blocks.set(meta.id, text);
416
460
  }
417
461
  if (gone.length === 0) {
418
- return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable), missing, viewable };
462
+ // A whole-document read is named only when one of the files is small enough for it.
463
+ const wholeReads = plan.searchable.some((meta) => canBeReadWhole(meta, budget));
464
+ return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads), missing, viewable };
419
465
  }
420
466
  missing.push(...gone);
421
467
  documents = documents.filter((meta) => !gone.includes(meta.id));
@@ -424,7 +470,6 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
424
470
 
425
471
  tools(documents, toolOptions = {}) {
426
472
  const { viewPages, ...rest } = toolOptions;
427
- const loadOriginal = options.store.getOriginal?.bind(options.store);
428
473
  const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
429
474
  .filter((meta) => meta.format === "pdf" && meta.originalKept);
430
475
  return createDocumentTools({
@@ -433,6 +478,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
433
478
  names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, meta.name])),
434
479
  budget,
435
480
  ...(loadOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal } : {}),
481
+ // `analyze_whole_document` is declared only when it can read at least one of the documents.
482
+ wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
436
483
  ...rest,
437
484
  });
438
485
  },
package/src/map-reduce.ts CHANGED
@@ -22,6 +22,16 @@ export type WholeDocumentResult = {
22
22
 
23
23
  type Parts = Array<{ from: number; to: number }>;
24
24
 
25
+ /**
26
+ * Whether a part's reply says that the part holds nothing for the task: the sentinel, whatever
27
+ * Markdown or punctuation a model puts around it (`**NOTHING RELEVANT**`). A reply that starts
28
+ * that way and then cites a line did find something, and is kept.
29
+ */
30
+ export function saysNothingRelevant(reply: string): boolean {
31
+ const text = reply.replace(/^[^\p{L}\p{N}]+/u, "");
32
+ return text.toUpperCase().startsWith(NOTHING) && !/\(L\d+/.test(text.slice(NOTHING.length));
33
+ }
34
+
25
35
  /** Splits a text, fed a piece at a time, into line ranges that each fit one model request. */
26
36
  class PartSplitter {
27
37
  private readonly maxTokens: number;
@@ -192,7 +202,7 @@ export async function analyzeWholeDocument(options: {
192
202
  // Nothing was read at all: an answer written from here would be invented.
193
203
  if (failed === parts.length) throw new Error(`Could not read any part of ${name}: ${firstFailure}`);
194
204
 
195
- const relevant = notes.filter((note) => !note.text.toUpperCase().startsWith(NOTHING));
205
+ const relevant = notes.filter((note) => !saysNothingRelevant(note.text));
196
206
  const relevantParts = relevant.filter((note) => note.read).length;
197
207
  if (relevantParts === 0) {
198
208
  return {
@@ -233,17 +243,30 @@ export async function analyzeWholeDocument(options: {
233
243
  for (let index = 0; index < layer.length; index += 2) batches.push(layer.slice(index, index + 2));
234
244
  }
235
245
  let combined = 0;
246
+ let unmerged = 0;
236
247
  layer = await pool(batches.length, options.concurrency ?? 4, async (index) => {
237
- const reply = await ask(generate, {
238
- system: "You merge partial notes about a document into shorter notes, keeping every relevant fact and line citation.",
239
- prompt: `Task: ${task}\n\nMerge these notes from ${name} into one set of notes. Keep line citations.\n\n${batches[index]!.join("\n\n")}`,
240
- maxOutputTokens: PART_OUTPUT_TOKENS,
241
- }, signal);
242
- if (reply.truncated) truncatedMerges++;
248
+ const batch = batches[index]!.join("\n\n");
249
+ let merged: string;
250
+ try {
251
+ const reply = await ask(generate, {
252
+ system: "You merge partial notes about a document into shorter notes, keeping every relevant fact and line citation.",
253
+ prompt: `Task: ${task}\n\nMerge these notes from ${name} into one set of notes. Keep line citations.\n\n${batch}`,
254
+ maxOutputTokens: PART_OUTPUT_TOKENS,
255
+ }, signal);
256
+ if (reply.truncated) truncatedMerges++;
257
+ merged = reply.truncated ? `${reply.text}\n[These merged notes were cut off at the output limit.]` : reply.text;
258
+ } catch (error) {
259
+ if (signal?.aborted) throw error;
260
+ // A merge that cannot be made loses nothing: the notes of every part were paid for, and go on as they are.
261
+ unmerged++;
262
+ merged = batch;
263
+ }
243
264
  combined++;
244
265
  onProgress?.({ kind: "reduce", message: `Combining notes on ${name} (round ${round}): ${combined} of ${batches.length}`, done: combined, total: batches.length });
245
- return reply.truncated ? `${reply.text}\n[These merged notes were cut off at the output limit.]` : reply.text;
266
+ return merged;
246
267
  }, signal);
268
+ // Notes that would not merge will not merge in another round either: the answer is written from what there is.
269
+ if (unmerged > 0) break;
247
270
  }
248
271
 
249
272
  onProgress?.({ kind: "reduce", message: `Writing the answer from ${relevantParts} relevant parts of ${name}`, done: 0, total: 1 });
package/src/plan.ts CHANGED
@@ -18,7 +18,7 @@ export function planDocuments(
18
18
  const byteRoom = budget.maxRequestBytes - REQUEST_BYTES_MARGIN - base.bytes;
19
19
  const plan: DocumentPlan = { inline: [], searchable: [], inlineTokens: 0, inlineBytes: 0 };
20
20
  for (const meta of [...documents].sort((left, right) => left.estimatedTokens - right.estimatedTokens)) {
21
- const bytes = Math.ceil(meta.textBytes * 1.08) + 200;
21
+ const bytes = (meta.jsonBytes ?? Math.ceil(meta.textBytes * 1.08)) + 200;
22
22
  if (plan.inlineTokens + meta.estimatedTokens <= tokenRoom && plan.inlineBytes + bytes <= byteRoom) {
23
23
  plan.inline.push(meta);
24
24
  plan.inlineTokens += meta.estimatedTokens;
@@ -30,6 +30,41 @@ export function planDocuments(
30
30
  return plan;
31
31
  }
32
32
 
33
+ /** The digits of the numbers 1 to `count`, written out: what the line numbers of a text take. */
34
+ function digitsUpTo(count: number): number {
35
+ let digits = 0;
36
+ for (let width = 1, first = 1; first <= count; width++, first *= 10) digits += (Math.min(count, first * 10 - 1) - first + 1) * width;
37
+ return digits;
38
+ }
39
+
40
+ /**
41
+ * About how many parts a whole-document read of a document takes, from its metadata alone:
42
+ * counting them exactly means reading the whole text. In the prompt every line carries its number
43
+ * (`12345| `), at about 1.2 tokens a digit and one for the bar, and each line's estimate is
44
+ * rounded up. A part ends at the end of a line, so it is short of full by half a line on average.
45
+ * On logs, prose, tables and blank-heavy text this lands within a few percent of the count.
46
+ */
47
+ export function estimateParts(meta: Pick<DocumentMeta, "estimatedTokens" | "lines" | "textBytes" | "jsonBytes">, budget: Budget): number {
48
+ const lines = Math.max(1, meta.lines);
49
+ const digits = digitsUpTo(lines);
50
+ const tokens = meta.estimatedTokens + 1.2 * digits + 1.5 * lines;
51
+ const bytes = (meta.jsonBytes ?? meta.textBytes * 1.08) + digits + 4 * lines;
52
+ const room = (limit: number, size: number) => Math.max(1, limit - size / lines / 2);
53
+ const maxBytes = Math.floor(budget.maxRequestBytes * 0.8);
54
+ return Math.max(1, Math.ceil(Math.max(tokens / room(budget.mapChunkTokens, tokens), bytes / room(maxBytes, bytes))));
55
+ }
56
+
57
+ /**
58
+ * Whether a whole-document read of a document is within `maxMapChunks`, as far as its metadata
59
+ * tells. The estimate runs a few percent high, so a file just over the limit by it is let through:
60
+ * the read counts its parts, and refuses with the reason if they are too many after all.
61
+ */
62
+ export function canBeReadWhole(meta: Pick<DocumentMeta, "estimatedTokens" | "lines" | "textBytes" | "jsonBytes">, budget: Budget): boolean {
63
+ const parts = estimateParts(meta, budget);
64
+ // Metadata that does not say (a record of a document that an application kept in part): not refused here.
65
+ return !Number.isFinite(parts) || parts <= budget.maxMapChunks * 1.05;
66
+ }
67
+
33
68
  function formatCount(value: number): string {
34
69
  if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
35
70
  if (value >= 10_000) return `${Math.round(value / 1_000)}K`;
@@ -59,14 +94,17 @@ export const CARD_LINES = CARD_HEAD_LINES;
59
94
  /**
60
95
  * A compact stand-in for a document that is too large for the prompt. `head` is its first
61
96
  * `CARD_LINES` lines, numbered. `viewable` adds a line saying that its pages can be looked at
62
- * with `view_pages`.
97
+ * with `view_pages`. `readableWhole` is false for a file that a whole-document read would refuse:
98
+ * the card then does not offer one.
63
99
  */
64
- export function renderCard(meta: DocumentMeta, head: string, viewable = false): string {
100
+ export function renderCard(meta: DocumentMeta, head: string, viewable = false, readableWhole = true): string {
65
101
  const out = [
66
102
  `--- Large attached file: ${meta.name} ---`,
67
103
  `document_id: ${meta.id}`,
68
104
  `${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} lines${meta.pages ? ` · ${meta.pages} pages` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
69
- "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.",
105
+ readableWhole
106
+ ? "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it."
107
+ : "This file is NOT in your context. Use the document tools to search it and to read line ranges. It is too large to be analyzed whole.",
70
108
  ...(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."] : []),
71
109
  ];
72
110
  const profile = meta.logProfile;
@@ -91,9 +129,10 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false):
91
129
  /**
92
130
  * The tool guide for the system prompt. `searchable` are the files the model reads through the
93
131
  * text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
94
- * may be searchable, and some may have their whole text in the prompt.
132
+ * may be searchable, and some may have their whole text in the prompt. `wholeReads` is false when
133
+ * every searchable file is too large for `analyze_whole_document`: the guide then leaves it out.
95
134
  */
96
- export function documentToolsInstruction(searchable: DocumentMeta[], viewable: DocumentMeta[] = []): string {
135
+ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: DocumentMeta[] = [], wholeReads = true): string {
97
136
  // File names come from uploads. Quoting keeps a name that reads like an instruction a name.
98
137
  const named = (meta: DocumentMeta, detail = "") => `${JSON.stringify(meta.name)} (document_id ${meta.id}${detail})`;
99
138
  const guide: string[] = [];
@@ -104,7 +143,7 @@ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: D
104
143
  "- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
105
144
  "- read_document reads a line range. Read around search hits before you rely on them.",
106
145
  "- get_document_overview returns the outline, log profile, and the start and end of a file.",
107
- "- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly.",
146
+ ...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly."] : []),
108
147
  "You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
109
148
  "Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.",
110
149
  );
package/src/ranged.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * text the first time an older document without one is opened, and saved for next time.
6
6
  */
7
7
  import type { Limiter } from "./limiter.js";
8
- import { pagesOfLines, type DocumentSource, type TextChunk } from "./search.js";
8
+ import { pagesOfLines, pause, type DocumentSource, type ScanFeed, type TextChunk } from "./search.js";
9
9
  import { canSerialize, parseTextIndex, positionOf, serializeTextIndex, TextIndexBuilder, type TextIndex } from "./text-index.js";
10
10
  import { foldCase, LineIndex } from "./text.js";
11
11
  import type { DocumentMeta, DocumentStore } from "./types.js";
@@ -49,7 +49,7 @@ const decoder = new TextDecoder("utf-8");
49
49
  const gone = (id: string) => new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
50
50
 
51
51
  /** A scan of a document: fed the pieces in order until it says it is done. */
52
- type Consumer = { feed: (chunk: TextChunk) => boolean | void; done: boolean; settle: (error?: unknown) => void };
52
+ type Consumer = { feed: ScanFeed; done: boolean; settle: (error?: unknown) => void };
53
53
 
54
54
  export class RangedDocument implements DocumentSource {
55
55
  /**
@@ -140,7 +140,7 @@ export class RangedDocument implements DocumentSource {
140
140
  * the pieces are then read, decoded and lowercased once, for all of them. A scan asked for once
141
141
  * the pass has started waits for the next one, since every scan must see the text from the start.
142
142
  */
143
- scan(feed: (chunk: TextChunk) => boolean | void, signal?: AbortSignal): Promise<void> {
143
+ scan(feed: ScanFeed, signal?: AbortSignal): Promise<void> {
144
144
  return new Promise<void>((resolve, reject) => {
145
145
  if (signal?.aborted) {
146
146
  reject(signal.reason);
@@ -184,14 +184,21 @@ export class RangedDocument implements DocumentSource {
184
184
  for (const consumer of group) {
185
185
  if (consumer.done) continue;
186
186
  try {
187
- if (consumer.feed(chunk) === true) consumer.settle();
188
- else open++;
187
+ let more = consumer.feed(chunk);
188
+ // A scan that asks for the same piece again has stopped part-way to let other work run.
189
+ while (more === "again" && !consumer.done) {
190
+ await pause();
191
+ slice = performance.now();
192
+ more = consumer.feed(chunk);
193
+ }
194
+ if (more === true) consumer.settle();
195
+ else if (!consumer.done) open++;
189
196
  } catch (error) {
190
197
  consumer.settle(error);
191
198
  }
192
199
  // Many scans on one piece add up: give other work (answers streaming to other users) a turn.
193
200
  if (performance.now() - slice > YIELD_AFTER_MS) {
194
- await new Promise((resolve) => setImmediate(resolve));
201
+ await pause();
195
202
  slice = performance.now();
196
203
  }
197
204
  }