llm-large-files 0.4.0 → 0.5.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 (156) hide show
  1. package/CHANGELOG.md +205 -0
  2. package/README.md +48 -8
  3. package/dist/anthropic/adapter.d.ts +106 -0
  4. package/dist/anthropic/adapter.d.ts.map +1 -0
  5. package/dist/anthropic/adapter.js +391 -0
  6. package/dist/anthropic/adapter.js.map +1 -0
  7. package/dist/anthropic/index.d.ts +3 -0
  8. package/dist/anthropic/index.d.ts.map +1 -0
  9. package/dist/anthropic/index.js +2 -0
  10. package/dist/anthropic/index.js.map +1 -0
  11. package/dist/ask.d.ts +144 -0
  12. package/dist/ask.d.ts.map +1 -0
  13. package/dist/ask.js +540 -0
  14. package/dist/ask.js.map +1 -0
  15. package/dist/budget.d.ts +23 -0
  16. package/dist/budget.d.ts.map +1 -0
  17. package/dist/budget.js +64 -0
  18. package/dist/budget.js.map +1 -0
  19. package/dist/cache.d.ts +11 -2
  20. package/dist/cache.d.ts.map +1 -1
  21. package/dist/cache.js +36 -7
  22. package/dist/cache.js.map +1 -1
  23. package/dist/errors.d.ts +21 -0
  24. package/dist/errors.d.ts.map +1 -0
  25. package/dist/errors.js +44 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/evidence.d.ts +40 -0
  28. package/dist/evidence.d.ts.map +1 -0
  29. package/dist/evidence.js +137 -0
  30. package/dist/evidence.js.map +1 -0
  31. package/dist/gemini/adapter.d.ts +50 -0
  32. package/dist/gemini/adapter.d.ts.map +1 -0
  33. package/dist/gemini/adapter.js +179 -0
  34. package/dist/gemini/adapter.js.map +1 -0
  35. package/dist/gemini/chat.d.ts +32 -71
  36. package/dist/gemini/chat.d.ts.map +1 -1
  37. package/dist/gemini/chat.js +38 -284
  38. package/dist/gemini/chat.js.map +1 -1
  39. package/dist/gemini/errors.d.ts +11 -0
  40. package/dist/gemini/errors.d.ts.map +1 -0
  41. package/dist/gemini/errors.js +14 -0
  42. package/dist/gemini/errors.js.map +1 -0
  43. package/dist/gemini/generate.d.ts +12 -13
  44. package/dist/gemini/generate.d.ts.map +1 -1
  45. package/dist/gemini/generate.js +62 -26
  46. package/dist/gemini/generate.js.map +1 -1
  47. package/dist/gemini/index.d.ts +3 -1
  48. package/dist/gemini/index.d.ts.map +1 -1
  49. package/dist/gemini/index.js +2 -1
  50. package/dist/gemini/index.js.map +1 -1
  51. package/dist/gemini/sse.d.ts +1 -2
  52. package/dist/gemini/sse.d.ts.map +1 -1
  53. package/dist/gemini/sse.js +1 -38
  54. package/dist/gemini/sse.js.map +1 -1
  55. package/dist/http.d.ts +20 -0
  56. package/dist/http.d.ts.map +1 -0
  57. package/dist/http.js +55 -0
  58. package/dist/http.js.map +1 -0
  59. package/dist/index.d.ts +14 -2
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +12 -4
  62. package/dist/index.js.map +1 -1
  63. package/dist/library.d.ts +50 -5
  64. package/dist/library.d.ts.map +1 -1
  65. package/dist/library.js +56 -26
  66. package/dist/library.js.map +1 -1
  67. package/dist/map-reduce.d.ts +15 -0
  68. package/dist/map-reduce.d.ts.map +1 -1
  69. package/dist/map-reduce.js +58 -27
  70. package/dist/map-reduce.js.map +1 -1
  71. package/dist/model.d.ts +196 -0
  72. package/dist/model.d.ts.map +1 -0
  73. package/dist/model.js +41 -0
  74. package/dist/model.js.map +1 -0
  75. package/dist/openai/adapter.d.ts +85 -0
  76. package/dist/openai/adapter.d.ts.map +1 -0
  77. package/dist/openai/adapter.js +293 -0
  78. package/dist/openai/adapter.js.map +1 -0
  79. package/dist/openai/index.d.ts +3 -0
  80. package/dist/openai/index.d.ts.map +1 -0
  81. package/dist/openai/index.js +2 -0
  82. package/dist/openai/index.js.map +1 -0
  83. package/dist/output-limit.d.ts +30 -0
  84. package/dist/output-limit.d.ts.map +1 -0
  85. package/dist/output-limit.js +92 -0
  86. package/dist/output-limit.js.map +1 -0
  87. package/dist/plan.d.ts +20 -4
  88. package/dist/plan.d.ts.map +1 -1
  89. package/dist/plan.js +44 -7
  90. package/dist/plan.js.map +1 -1
  91. package/dist/ranged.d.ts +2 -2
  92. package/dist/ranged.d.ts.map +1 -1
  93. package/dist/ranged.js +11 -4
  94. package/dist/ranged.js.map +1 -1
  95. package/dist/retry.d.ts +54 -0
  96. package/dist/retry.d.ts.map +1 -0
  97. package/dist/retry.js +111 -0
  98. package/dist/retry.js.map +1 -0
  99. package/dist/search.d.ts +16 -2
  100. package/dist/search.d.ts.map +1 -1
  101. package/dist/search.js +109 -26
  102. package/dist/search.js.map +1 -1
  103. package/dist/sse.d.ts +3 -0
  104. package/dist/sse.d.ts.map +1 -0
  105. package/dist/sse.js +39 -0
  106. package/dist/sse.js.map +1 -0
  107. package/dist/stores.d.ts +5 -1
  108. package/dist/stores.d.ts.map +1 -1
  109. package/dist/stores.js +58 -15
  110. package/dist/stores.js.map +1 -1
  111. package/dist/text.d.ts +12 -1
  112. package/dist/text.d.ts.map +1 -1
  113. package/dist/text.js +43 -15
  114. package/dist/text.js.map +1 -1
  115. package/dist/tools.d.ts +23 -0
  116. package/dist/tools.d.ts.map +1 -1
  117. package/dist/tools.js +115 -35
  118. package/dist/tools.js.map +1 -1
  119. package/dist/types.d.ts +33 -3
  120. package/dist/types.d.ts.map +1 -1
  121. package/docs/api.md +253 -28
  122. package/docs/configuration.md +89 -10
  123. package/docs/getting-started.md +69 -16
  124. package/docs/how-it-works.md +46 -4
  125. package/docs/security.md +36 -3
  126. package/package.json +21 -3
  127. package/src/anthropic/adapter.ts +454 -0
  128. package/src/anthropic/index.ts +2 -0
  129. package/src/ask.ts +675 -0
  130. package/src/budget.ts +71 -0
  131. package/src/cache.ts +32 -8
  132. package/src/errors.ts +42 -0
  133. package/src/evidence.ts +162 -0
  134. package/src/gemini/adapter.ts +218 -0
  135. package/src/gemini/chat.ts +62 -333
  136. package/src/gemini/errors.ts +15 -0
  137. package/src/gemini/generate.ts +72 -30
  138. package/src/gemini/index.ts +3 -1
  139. package/src/gemini/sse.ts +1 -34
  140. package/src/http.ts +59 -0
  141. package/src/index.ts +34 -4
  142. package/src/library.ts +102 -29
  143. package/src/map-reduce.ts +52 -23
  144. package/src/model.ts +200 -0
  145. package/src/openai/adapter.ts +345 -0
  146. package/src/openai/index.ts +2 -0
  147. package/src/output-limit.ts +99 -0
  148. package/src/plan.ts +46 -7
  149. package/src/ranged.ts +13 -6
  150. package/src/retry.ts +132 -0
  151. package/src/search.ts +116 -25
  152. package/src/sse.ts +34 -0
  153. package/src/stores.ts +51 -15
  154. package/src/text.ts +39 -12
  155. package/src/tools.ts +127 -38
  156. package/src/types.ts +29 -3
package/src/http.ts ADDED
@@ -0,0 +1,59 @@
1
+ // Small things every adapter needs for its HTTP requests.
2
+
3
+ /** Request headers, or a function returning them: called for each request, so a token can be renewed. */
4
+ export type HeaderSource = Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
5
+
6
+ export async function resolveHeaderSource(source: HeaderSource | undefined): Promise<Record<string, string>> {
7
+ return typeof source === "function" ? source() : source ?? {};
8
+ }
9
+
10
+ /** A secret, or a function returning it: called for each request. */
11
+ export type SecretSource = string | (() => string | Promise<string>);
12
+
13
+ export async function resolveSecret(source: SecretSource | undefined): Promise<string | undefined> {
14
+ return typeof source === "function" ? source() : source;
15
+ }
16
+
17
+ /** Base64 of bytes, worked out once for each array: the pages of a PDF are sent again with every later request. */
18
+ const encoded = new WeakMap<Uint8Array, string>();
19
+ export function base64(bytes: Uint8Array): string {
20
+ let text = encoded.get(bytes);
21
+ if (text === undefined) {
22
+ text = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
23
+ encoded.set(bytes, text);
24
+ }
25
+ return text;
26
+ }
27
+
28
+ /** The reason a request never got an answer, without the stack of the HTTP client. */
29
+ export function unreachableReason(error: unknown): string {
30
+ return error instanceof Error && error.message ? ` (${error.message})` : "";
31
+ }
32
+
33
+ /**
34
+ * Arguments of a tool call that arrived as JSON text, and, when the text is not a JSON object,
35
+ * why the call cannot be run: a model that is told so sends the call again.
36
+ */
37
+ export function readArguments(text: unknown): { args: Record<string, unknown>; problem?: string } {
38
+ if (text && typeof text === "object" && !Array.isArray(text)) return { args: text as Record<string, unknown> };
39
+ if (typeof text !== "string" || !text.trim()) return { args: {} };
40
+ try {
41
+ const value = JSON.parse(text) as unknown;
42
+ if (value && typeof value === "object" && !Array.isArray(value)) return { args: value as Record<string, unknown> };
43
+ } catch {
44
+ // Reported below.
45
+ }
46
+ return { args: {}, problem: `The arguments of this call were not a JSON object, and it was not run: ${text.slice(0, 300)}. Send the call again.` };
47
+ }
48
+
49
+ /** Arguments of a tool call that arrived as JSON text. Text that is no JSON object gives none. */
50
+ export function parseArguments(text: unknown): Record<string, unknown> {
51
+ if (text && typeof text === "object" && !Array.isArray(text)) return text as Record<string, unknown>;
52
+ if (typeof text !== "string" || !text.trim()) return {};
53
+ try {
54
+ const value = JSON.parse(text) as unknown;
55
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
56
+ } catch {
57
+ return {};
58
+ }
59
+ }
package/src/index.ts CHANGED
@@ -1,10 +1,40 @@
1
- // Core: provider-neutral. Gemini helpers live in "llm-large-files/gemini",
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";
1
+ // Core: provider-neutral. The tool loop is `askWithFiles`, and a model provider is an adapter:
2
+ // "llm-large-files/gemini", "llm-large-files/openai", "llm-large-files/anthropic", or your own.
3
+ // Node HTTP handlers are in "llm-large-files/node".
4
+ export { createLargeFiles, DEFAULT_CACHE_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, NEVER_EXPIRES, toDocumentSummary } from "./library.js";
4
5
  export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, PrepareOptions, ToolOptions } from "./library.js";
6
+ export { DEFAULT_BUDGET, resolveBudget } from "./budget.js";
7
+ export type { ModelLimits } from "./budget.js";
8
+ export { askWithFiles, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS } from "./ask.js";
9
+ export type { AskLimits, AskOptions, AskResult } from "./ask.js";
10
+ export { DocumentsNotFoundError, ModelRequestError, UsageMeter } from "./model.js";
11
+ export type {
12
+ ChatMessage,
13
+ ChatTurn,
14
+ ModelAdapter,
15
+ ModelCapabilities,
16
+ ModelMessage,
17
+ ModelPart,
18
+ ModelReply,
19
+ ModelRequest,
20
+ ModelTextMessage,
21
+ ModelToolRound,
22
+ ModelUsage,
23
+ SendHooks,
24
+ ToolAnswer,
25
+ ToolCall,
26
+ ToolTurn,
27
+ UsageTotals,
28
+ } from "./model.js";
29
+ export { evidenceOf, mergeRanges, stubResult } from "./evidence.js";
30
+ export type { Evidence, NumberRange } from "./evidence.js";
31
+ export { isRetryableStatus, retryAfterMs, withRetry } from "./retry.js";
32
+ export type { RetryOptions } from "./retry.js";
33
+ export { parseSseJson } from "./sse.js";
34
+ export { DocumentStoreError } from "./errors.js";
5
35
  export { FileDocumentStore, MemoryDocumentStore, DOCUMENT_ID_PATTERN } from "./stores.js";
6
36
  export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
7
37
  export type { PdfExtractorOptions } from "./extract.js";
8
38
  export { estimateTokens, utf8Bytes, jsonBytes } from "./text.js";
9
- export { MAX_VIEW_PAGES, TOOL_NAMES, toolResultSummary } from "./tools.js";
39
+ export { MAX_VIEW_PAGES, MAX_WHOLE_DOCUMENT_READS, REGEX_BUDGET_MS, TOOL_NAMES, toolResultSummary } from "./tools.js";
10
40
  export type * from "./types.js";
package/src/library.ts CHANGED
@@ -1,14 +1,17 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { buildLogProfile, buildOutline, looksLikeLog } from "./analyze.js";
3
+ import { givenBudget, resolveBudget, type ModelLimits } from "./budget.js";
3
4
  import { DocumentCache, documentVersion, type Sized } from "./cache.js";
5
+ import { DocumentStoreError } from "./errors.js";
4
6
  import { detectFormat, extractText } from "./extract.js";
5
7
  import { Limiter } from "./limiter.js";
6
- import { CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
8
+ import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
7
9
  import { openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
8
10
  import { numberLines, SearchableDocument, type DocumentSource } from "./search.js";
9
11
  import { DOCUMENT_ID_PATTERN } from "./stores.js";
10
12
  import { buildTextIndex, canSerialize, serializeTextIndex } from "./text-index.js";
11
- import { estimateTokens, normalizeText, utf8Bytes, wrapLongLines } from "./text.js";
13
+ import { estimateTokens, normalizeText, textSizes, wrapLongLines } from "./text.js";
14
+ import type { RetryOptions } from "./retry.js";
12
15
  import { createDocumentTools } from "./tools.js";
13
16
  import type {
14
17
  Budget,
@@ -23,23 +26,21 @@ import type {
23
26
  ToolSet,
24
27
  } from "./types.js";
25
28
 
26
- /** Defaults sized for a 1M-token model behind a 10 MB request limit. */
27
- export const DEFAULT_BUDGET: Budget = {
28
- contextTokens: 1_000_000,
29
- maxRequestBytes: 10_000_000,
30
- inlineTokens: 200_000,
31
- reservedTokens: 64_000,
32
- mapChunkTokens: 100_000,
33
- maxMapChunks: 30,
34
- toolResultCharacters: 24_000,
35
- };
29
+ export { DEFAULT_BUDGET } from "./budget.js";
36
30
 
37
31
  export type LargeFilesOptions = {
38
32
  /** Where extracted text is kept: `new FileDocumentStore(dir)`, `new MemoryDocumentStore()`, or your own. */
39
33
  store: DocumentStore;
40
- /** Your model's limits. Anything left out uses DEFAULT_BUDGET. */
34
+ /**
35
+ * Your model's limits. What is left out follows `contextTokens` (see `resolveBudget`), which is
36
+ * 1M tokens unless you set it: for a model with a smaller window, setting that one number is
37
+ * enough. Values that cannot work together are an error.
38
+ */
41
39
  budget?: Partial<Budget>;
42
- /** How long uploaded documents are kept. Defaults to 72 hours. */
40
+ /**
41
+ * How long uploaded documents are kept. Defaults to 72 hours. `Infinity` keeps them until they
42
+ * are deleted: their `expiresAt` is then `NEVER_EXPIRES`.
43
+ */
43
44
  ttlMs?: number;
44
45
  /** Largest accepted upload. Defaults to 100 MB. */
45
46
  maxUploadBytes?: number;
@@ -65,7 +66,11 @@ export type LargeFilesOptions = {
65
66
  * deleted or expired on another server sharing the store is never served from memory here.
66
67
  */
67
68
  cacheBytes?: number;
68
- /** Also caps the number of documents kept (the only limit before 0.4). Unset: no cap on the number. */
69
+ /**
70
+ * Also caps the number of documents kept (the only limit before 0.4). Unset: no cap on the
71
+ * number. The pieces kept of a document that is read by range are not counted, and go when
72
+ * their document does.
73
+ */
69
74
  cacheSize?: number;
70
75
  /**
71
76
  * Documents whose text is at most this many bytes are loaded whole into memory (and kept there
@@ -98,6 +103,11 @@ export type IngestInput = {
98
103
  export type AccessOptions = { owner?: string };
99
104
 
100
105
  export type PrepareOptions = AccessOptions & {
106
+ /**
107
+ * The budget of this request, when it is not the library's own: the fields to change, as in
108
+ * `LargeFilesOptions.budget`. `askWithFiles` passes the budget that fits the model it was given.
109
+ */
110
+ budget?: Partial<Budget>;
101
111
  /**
102
112
  * Say that your tool loop can pass files to the model (see `ToolOptions.viewPages`). The result
103
113
  * then lists the PDFs whose pages can be shown in `viewable`, and the instruction and the cards
@@ -112,6 +122,23 @@ export type ToolOptions = {
112
122
  /** Progress of whole-document reads, for status messages. */
113
123
  onProgress?: ProgressListener;
114
124
  signal?: AbortSignal;
125
+ /**
126
+ * The most time, in milliseconds, that the regex searches of this tool set may take together.
127
+ * Past it, a regex search answers with an error that tells the model to search another way.
128
+ * Defaults to 6,000. One search still stops after 3,000, and at once at a line its pattern
129
+ * cannot get past.
130
+ */
131
+ regexBudgetMs?: number;
132
+ /**
133
+ * How many times each document may be read whole (`analyze_whole_document`) by this tool set.
134
+ * A call past it answers with an error that tells the model to use what it has. Defaults to 1:
135
+ * make one tool set for each question, as `askWithFiles` does.
136
+ */
137
+ maxWholeDocumentReads?: number;
138
+ /** How a model request of a whole-document read that failed is sent again. Defaults to three more tries, with a wait that doubles. */
139
+ retry?: RetryOptions;
140
+ /** The budget of these tools, when it is not the library's own: the fields to change. Use the one you planned the request with. */
141
+ budget?: Partial<Budget>;
115
142
  /**
116
143
  * Offers `view_pages`, which hands the model real pages of a PDF whose original file is kept
117
144
  * (see `keepOriginals`). The pages come back as a file, so turn this on only when your loop
@@ -125,6 +152,12 @@ export type ToolOptions = {
125
152
  export interface LargeFiles {
126
153
  /** The effective budget (defaults merged with your overrides). */
127
154
  readonly budget: Budget;
155
+ /**
156
+ * The budget for one request: the library's, with `overrides` in place of its fields, made to
157
+ * fit `limits` (a model's context window and request size, when they are smaller). Fields that
158
+ * neither the library nor `overrides` set follow the context window that results.
159
+ */
160
+ budgetFor(overrides?: Partial<Budget>, limits?: ModelLimits): Budget;
128
161
  readonly maxUploadBytes: number;
129
162
  /** Extracts, normalizes, profiles, and stores a file. Throws a user-readable Error on bad input. */
130
163
  ingest(input: IngestInput): Promise<DocumentMeta>;
@@ -177,6 +210,24 @@ export function cleanFileName(raw: string): string {
177
210
  .slice(0, 255) || "file";
178
211
  }
179
212
 
213
+ /**
214
+ * A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
215
+ * could not be read is not a document that is gone, and its own error names paths or hosts.
216
+ */
217
+ async function reading<T>(read: () => Promise<T>): Promise<T> {
218
+ try {
219
+ return await read();
220
+ } catch (error) {
221
+ throw error instanceof DocumentStoreError ? error : new DocumentStoreError(error);
222
+ }
223
+ }
224
+
225
+ /**
226
+ * The `expiresAt` of a document that never expires (`ttlMs: Infinity`): the last instant of the
227
+ * year 9999. A date, so that every comparison, and a server of an older version, reads it as any other.
228
+ */
229
+ export const NEVER_EXPIRES = "9999-12-31T23:59:59.999Z";
230
+
180
231
  function allowed(meta: DocumentMeta, access: AccessOptions | undefined): boolean {
181
232
  return meta.owner === undefined || meta.owner === access?.owner;
182
233
  }
@@ -187,7 +238,12 @@ export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
187
238
  export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
188
239
 
189
240
  export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
190
- const budget: Budget = { ...DEFAULT_BUDGET, ...options.budget };
241
+ /** The fields the application set. The others follow the context window, whichever it is for a request. */
242
+ const ownBudget = givenBudget(options.budget);
243
+ const budget: Budget = resolveBudget(ownBudget);
244
+ const budgetFor = (overrides?: Partial<Budget>, limits?: ModelLimits): Budget => (
245
+ overrides || limits ? resolveBudget({ ...ownBudget, ...givenBudget(overrides) }, limits) : budget
246
+ );
191
247
  const ttlMs = options.ttlMs ?? 72 * 60 * 60 * 1000;
192
248
  const maxUploadBytes = options.maxUploadBytes ?? 100 * 1024 * 1024;
193
249
  const now = options.now ?? (() => new Date());
@@ -206,7 +262,13 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
206
262
  /** Documents being opened, so that calls arriving together open each one once. */
207
263
  const opening = new Map<string, Promise<DocumentSource | undefined>>();
208
264
  /** 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;
265
+ const ranged: RangeStore | undefined = typeof store.readTextRange === "function" ? {
266
+ readTextRange: (id, start, end) => reading(() => store.readTextRange!(id, start, end)),
267
+ ...(store.getIndex ? { getIndex: (id: string) => reading(() => store.getIndex!(id)) } : {}),
268
+ ...(store.putIndex ? { putIndex: (id: string, index: Uint8Array) => store.putIndex!(id, index) } : {}),
269
+ } : undefined;
270
+ /** The uploaded file of a document, when the store keeps such files. */
271
+ const loadOriginal = store.getOriginal ? (id: string) => reading(() => store.getOriginal!(id)) : undefined;
210
272
  const wholeDocumentBytes = Math.max(0, options.wholeDocumentBytes ?? DEFAULT_WHOLE_DOCUMENT_BYTES);
211
273
  /** Documents whose saved index did not match their text: the next opening builds it from the text. */
212
274
  const rebuildIndex = new Set<string>();
@@ -219,7 +281,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
219
281
  },
220
282
  pieces: {
221
283
  get: (key, version) => cache.get(key, version) as CachedPiece | undefined,
222
- set: (key, version, piece) => cache.set(key, version, piece),
284
+ // A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with it.
285
+ set: (key, version, piece) => cache.set(key, version, piece, key.slice(0, key.indexOf("#"))),
223
286
  // A quarter of the cache: a few documents can be kept, and no one pushes out all the rest.
224
287
  maxDocumentBytes: cacheBytes / 4,
225
288
  },
@@ -235,7 +298,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
235
298
  */
236
299
  async function currentMeta(id: string): Promise<DocumentMeta | undefined> {
237
300
  if (!isDocumentId(id)) return undefined;
238
- const meta = await options.store.getMeta(id);
301
+ const meta = await reading(() => store.getMeta(id));
239
302
  if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
240
303
  forget(id);
241
304
  return undefined;
@@ -271,7 +334,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
271
334
  const rebuild = rebuildIndex.delete(id);
272
335
  return openRangedDocument(ranged, meta, scan, { ignoreSavedIndex: rebuild });
273
336
  }
274
- const stored = await store.get(id);
337
+ const stored = await reading(() => store.get(id));
275
338
  return stored ? new SearchableDocument(stored) : undefined;
276
339
  }
277
340
 
@@ -279,14 +342,14 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
279
342
  * What a document contributes to the prompt: its text, or its card. Undefined when it is gone
280
343
  * by now. A copy found to disagree with the store is opened again once.
281
344
  */
282
- async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean): Promise<string | undefined> {
345
+ async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean, readableWhole: boolean): Promise<string | undefined> {
283
346
  for (let attempt = 0; attempt < 2; attempt++) {
284
347
  const document = await load(id, attempt === 0 ? meta : undefined);
285
348
  if (!document) return undefined;
286
349
  try {
287
350
  return whole
288
351
  ? renderInline(document.meta, await document.readText())
289
- : renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable);
352
+ : renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, readableWhole);
290
353
  } catch (error) {
291
354
  if (!document.broken) {
292
355
  // Deleted between the look-up and the read: the same as missing.
@@ -305,6 +368,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
305
368
 
306
369
  return {
307
370
  budget,
371
+ budgetFor,
308
372
  maxUploadBytes,
309
373
 
310
374
  async ingest(input) {
@@ -328,6 +392,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
328
392
  if (text.endsWith("\n")) lines.pop();
329
393
  if (format === "text" && looksLikeLog(lines)) format = "log";
330
394
  const created = now();
395
+ const expires = created.getTime() + ttlMs;
396
+ const sizes = textSizes(text);
331
397
  const keepOriginal = keeps(format);
332
398
  const meta: DocumentMeta = {
333
399
  id: `doc_${randomUUID().replaceAll("-", "")}`,
@@ -336,7 +402,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
336
402
  mimeType,
337
403
  format,
338
404
  bytes: input.bytes.byteLength,
339
- textBytes: utf8Bytes(text),
405
+ textBytes: sizes.utf8,
406
+ jsonBytes: sizes.json,
340
407
  characters: text.length,
341
408
  lines: lines.length,
342
409
  estimatedTokens: estimateTokens(text),
@@ -346,7 +413,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
346
413
  outline: buildOutline(lines, format),
347
414
  ...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
348
415
  createdAt: created.toISOString(),
349
- expiresAt: new Date(created.getTime() + ttlMs).toISOString(),
416
+ // Never, for a time to live without end (or one that runs past what a date can hold).
417
+ expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
350
418
  };
351
419
  // The line index, so that the text can be read by range: a few bytes a line, built from the
352
420
  // UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
@@ -373,7 +441,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
373
441
 
374
442
  async getOriginal(id, access) {
375
443
  const meta = await metaFor(id, access);
376
- return meta?.originalKept ? options.store.getOriginal?.(id) : undefined;
444
+ return meta?.originalKept ? loadOriginal?.(id) : undefined;
377
445
  },
378
446
 
379
447
  async delete(id, access) {
@@ -387,6 +455,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
387
455
  },
388
456
 
389
457
  async prepare(ids, base, access) {
458
+ const budget = budgetFor(access?.budget);
390
459
  const unique = [...new Set(ids)];
391
460
  let documents: DocumentMeta[] = [];
392
461
  const missing: string[] = [];
@@ -410,12 +479,14 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
410
479
  const blocks = new Map<string, string>();
411
480
  const gone: string[] = [];
412
481
  for (const meta of documents) {
413
- const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id));
482
+ const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), canBeReadWhole(meta, budget));
414
483
  if (text === undefined) gone.push(meta.id);
415
484
  else blocks.set(meta.id, text);
416
485
  }
417
486
  if (gone.length === 0) {
418
- return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable), missing, viewable };
487
+ // A whole-document read is named only when one of the files is small enough for it.
488
+ const wholeReads = plan.searchable.some((meta) => canBeReadWhole(meta, budget));
489
+ return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads), missing, viewable };
419
490
  }
420
491
  missing.push(...gone);
421
492
  documents = documents.filter((meta) => !gone.includes(meta.id));
@@ -423,8 +494,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
423
494
  },
424
495
 
425
496
  tools(documents, toolOptions = {}) {
426
- const { viewPages, ...rest } = toolOptions;
427
- const loadOriginal = options.store.getOriginal?.bind(options.store);
497
+ const { viewPages, budget: overrides, ...rest } = toolOptions;
498
+ const budget = budgetFor(overrides);
428
499
  const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
429
500
  .filter((meta) => meta.format === "pdf" && meta.originalKept);
430
501
  return createDocumentTools({
@@ -433,6 +504,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
433
504
  names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, meta.name])),
434
505
  budget,
435
506
  ...(loadOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal } : {}),
507
+ // `analyze_whole_document` is declared only when it can read at least one of the documents.
508
+ wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
436
509
  ...rest,
437
510
  });
438
511
  },
package/src/map-reduce.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { withRetry, type RetryOptions } from "./retry.js";
1
2
  import { estimateTokens, jsonBytes } from "./text.js";
2
3
  import { numberLines, scanSource, SearchableDocument, type DocumentSource, type TextChunk } from "./search.js";
3
4
  import type { Budget, GenerateText, ProgressListener } from "./types.js";
@@ -22,6 +23,16 @@ export type WholeDocumentResult = {
22
23
 
23
24
  type Parts = Array<{ from: number; to: number }>;
24
25
 
26
+ /**
27
+ * Whether a part's reply says that the part holds nothing for the task: the sentinel, whatever
28
+ * Markdown or punctuation a model puts around it (`**NOTHING RELEVANT**`). A reply that starts
29
+ * that way and then cites a line did find something, and is kept.
30
+ */
31
+ export function saysNothingRelevant(reply: string): boolean {
32
+ const text = reply.replace(/^[^\p{L}\p{N}]+/u, "");
33
+ return text.toUpperCase().startsWith(NOTHING) && !/\(L\d+/.test(text.slice(NOTHING.length));
34
+ }
35
+
25
36
  /** Splits a text, fed a piece at a time, into line ranges that each fit one model request. */
26
37
  class PartSplitter {
27
38
  private readonly maxTokens: number;
@@ -104,26 +115,31 @@ async function pool<T>(count: number, concurrency: number, run: (index: number)
104
115
  return results;
105
116
  }
106
117
 
107
- async function withRetry(call: () => Promise<string>, signal?: AbortSignal): Promise<string> {
108
- try {
109
- return await call();
110
- } catch (error) {
111
- if (signal?.aborted) throw error;
112
- return call();
118
+ /** A whole-document read that was refused before any model call: the document has too many parts. */
119
+ export class TooManyPartsError extends Error {
120
+ constructor(name: string, readonly parts: number, readonly limit: number) {
121
+ super(`Reading all of ${name} needs ${parts} model calls, over the limit of ${limit}. Use search_document to narrow the question first.`);
122
+ this.name = "TooManyPartsError";
113
123
  }
114
124
  }
115
125
 
116
- /** One model call, retried once. `truncated` is true when the reply that was kept hit the output limit. */
126
+ /**
127
+ * One model call. A model that was busy or failed on its side (an error with an HTTP status worth
128
+ * retrying) is asked again after a wait, a few times; a request it refused is not. An error that
129
+ * says nothing of the kind is tried once more, at once. `truncated` is true when the reply that
130
+ * was kept hit the output limit.
131
+ */
117
132
  async function ask(
118
133
  generate: GenerateText,
119
134
  request: { system: string; prompt: string; maxOutputTokens: number },
120
135
  signal: AbortSignal | undefined,
136
+ retry: RetryOptions | undefined,
121
137
  ): Promise<{ text: string; truncated: boolean }> {
122
138
  let truncated = false;
123
139
  const text = await withRetry(() => {
124
140
  truncated = false;
125
- return generate({ ...request, signal, onTruncated: () => { truncated = true; } });
126
- }, signal);
141
+ return generate({ ...request, ...(signal ? { signal } : {}), onTruncated: () => { truncated = true; } });
142
+ }, { retry, signal, unknownErrors: "once" });
127
143
  return { text: text.trim(), truncated };
128
144
  }
129
145
 
@@ -139,13 +155,13 @@ export async function analyzeWholeDocument(options: {
139
155
  onProgress?: ProgressListener;
140
156
  signal?: AbortSignal;
141
157
  concurrency?: number;
158
+ /** How a model request that failed is sent again. See `RetryOptions`. */
159
+ retry?: RetryOptions;
142
160
  }): Promise<WholeDocumentResult> {
143
- const { document, task, generate, budget, onProgress, signal } = options;
161
+ const { document, task, generate, budget, onProgress, signal, retry } = options;
144
162
  const name = document.meta.name;
145
163
  const parts = await partsOf(document, budget, signal);
146
- if (parts.length > budget.maxMapChunks) {
147
- throw new Error(`Reading all of ${name} needs ${parts.length} model calls, over the limit of ${budget.maxMapChunks}. Use search_document to narrow the question first.`);
148
- }
164
+ if (parts.length > budget.maxMapChunks) throw new TooManyPartsError(name, parts.length, budget.maxMapChunks);
149
165
 
150
166
  let done = 0;
151
167
  let failed = 0;
@@ -170,7 +186,7 @@ export async function analyzeWholeDocument(options: {
170
186
  "</part>",
171
187
  ].join("\n"),
172
188
  maxOutputTokens: PART_OUTPUT_TOKENS,
173
- }, signal);
189
+ }, signal, retry);
174
190
  text = reply.text;
175
191
  if (reply.truncated) {
176
192
  truncatedParts++;
@@ -192,7 +208,7 @@ export async function analyzeWholeDocument(options: {
192
208
  // Nothing was read at all: an answer written from here would be invented.
193
209
  if (failed === parts.length) throw new Error(`Could not read any part of ${name}: ${firstFailure}`);
194
210
 
195
- const relevant = notes.filter((note) => !note.text.toUpperCase().startsWith(NOTHING));
211
+ const relevant = notes.filter((note) => !saysNothingRelevant(note.text));
196
212
  const relevantParts = relevant.filter((note) => note.read).length;
197
213
  if (relevantParts === 0) {
198
214
  return {
@@ -233,17 +249,30 @@ export async function analyzeWholeDocument(options: {
233
249
  for (let index = 0; index < layer.length; index += 2) batches.push(layer.slice(index, index + 2));
234
250
  }
235
251
  let combined = 0;
252
+ let unmerged = 0;
236
253
  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++;
254
+ const batch = batches[index]!.join("\n\n");
255
+ let merged: string;
256
+ try {
257
+ const reply = await ask(generate, {
258
+ system: "You merge partial notes about a document into shorter notes, keeping every relevant fact and line citation.",
259
+ prompt: `Task: ${task}\n\nMerge these notes from ${name} into one set of notes. Keep line citations.\n\n${batch}`,
260
+ maxOutputTokens: PART_OUTPUT_TOKENS,
261
+ }, signal, retry);
262
+ if (reply.truncated) truncatedMerges++;
263
+ merged = reply.truncated ? `${reply.text}\n[These merged notes were cut off at the output limit.]` : reply.text;
264
+ } catch (error) {
265
+ if (signal?.aborted) throw error;
266
+ // A merge that cannot be made loses nothing: the notes of every part were paid for, and go on as they are.
267
+ unmerged++;
268
+ merged = batch;
269
+ }
243
270
  combined++;
244
271
  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;
272
+ return merged;
246
273
  }, signal);
274
+ // Notes that would not merge will not merge in another round either: the answer is written from what there is.
275
+ if (unmerged > 0) break;
247
276
  }
248
277
 
249
278
  onProgress?.({ kind: "reduce", message: `Writing the answer from ${relevantParts} relevant parts of ${name}`, done: 0, total: 1 });
@@ -260,7 +289,7 @@ export async function analyzeWholeDocument(options: {
260
289
  layer.join("\n\n"),
261
290
  ].join("\n"),
262
291
  maxOutputTokens: FINAL_OUTPUT_TOKENS,
263
- }, signal);
292
+ }, signal, retry);
264
293
  return {
265
294
  answer: final.text,
266
295
  parts: parts.length,