llm-large-files 0.5.0 → 0.7.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 (221) hide show
  1. package/CHANGELOG.md +1402 -467
  2. package/README.md +188 -60
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +190 -39
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +60 -4
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1068 -206
  14. package/dist/ask.js.map +1 -1
  15. package/dist/encoding.d.ts +17 -0
  16. package/dist/encoding.d.ts.map +1 -0
  17. package/dist/encoding.js +852 -0
  18. package/dist/encoding.js.map +1 -0
  19. package/dist/errors.d.ts +4 -0
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +15 -0
  22. package/dist/errors.js.map +1 -1
  23. package/dist/events.d.ts +333 -0
  24. package/dist/events.d.ts.map +1 -0
  25. package/dist/events.js +159 -0
  26. package/dist/events.js.map +1 -0
  27. package/dist/evidence.d.ts +2 -0
  28. package/dist/evidence.d.ts.map +1 -1
  29. package/dist/evidence.js +3 -2
  30. package/dist/evidence.js.map +1 -1
  31. package/dist/extract.d.ts +35 -3
  32. package/dist/extract.d.ts.map +1 -1
  33. package/dist/extract.js +626 -58
  34. package/dist/extract.js.map +1 -1
  35. package/dist/gemini/adapter.d.ts +17 -8
  36. package/dist/gemini/adapter.d.ts.map +1 -1
  37. package/dist/gemini/adapter.js +108 -61
  38. package/dist/gemini/adapter.js.map +1 -1
  39. package/dist/gemini/chat.d.ts +23 -3
  40. package/dist/gemini/chat.d.ts.map +1 -1
  41. package/dist/gemini/chat.js +6 -2
  42. package/dist/gemini/chat.js.map +1 -1
  43. package/dist/gemini/errors.d.ts +9 -4
  44. package/dist/gemini/errors.d.ts.map +1 -1
  45. package/dist/gemini/errors.js +32 -0
  46. package/dist/gemini/errors.js.map +1 -1
  47. package/dist/gemini/generate.d.ts +10 -2
  48. package/dist/gemini/generate.d.ts.map +1 -1
  49. package/dist/gemini/generate.js +13 -7
  50. package/dist/gemini/generate.js.map +1 -1
  51. package/dist/gemini/index.d.ts +3 -3
  52. package/dist/gemini/index.d.ts.map +1 -1
  53. package/dist/gemini/index.js +2 -2
  54. package/dist/gemini/index.js.map +1 -1
  55. package/dist/gemini/sse.d.ts +1 -1
  56. package/dist/gemini/sse.d.ts.map +1 -1
  57. package/dist/gemini/sse.js +1 -1
  58. package/dist/gemini/sse.js.map +1 -1
  59. package/dist/http.d.ts +116 -0
  60. package/dist/http.d.ts.map +1 -1
  61. package/dist/http.js +347 -1
  62. package/dist/http.js.map +1 -1
  63. package/dist/index.d.ts +11 -6
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +6 -4
  66. package/dist/index.js.map +1 -1
  67. package/dist/library.d.ts +67 -5
  68. package/dist/library.d.ts.map +1 -1
  69. package/dist/library.js +405 -85
  70. package/dist/library.js.map +1 -1
  71. package/dist/map-reduce.d.ts +28 -1
  72. package/dist/map-reduce.d.ts.map +1 -1
  73. package/dist/map-reduce.js +240 -52
  74. package/dist/map-reduce.js.map +1 -1
  75. package/dist/model.d.ts +84 -2
  76. package/dist/model.d.ts.map +1 -1
  77. package/dist/model.js +182 -1
  78. package/dist/model.js.map +1 -1
  79. package/dist/node/handlers.d.ts +20 -4
  80. package/dist/node/handlers.d.ts.map +1 -1
  81. package/dist/node/handlers.js +122 -20
  82. package/dist/node/handlers.js.map +1 -1
  83. package/dist/node/index.d.ts +2 -0
  84. package/dist/node/index.d.ts.map +1 -1
  85. package/dist/node/index.js +1 -0
  86. package/dist/node/index.js.map +1 -1
  87. package/dist/node/sse.d.ts +59 -0
  88. package/dist/node/sse.d.ts.map +1 -0
  89. package/dist/node/sse.js +174 -0
  90. package/dist/node/sse.js.map +1 -0
  91. package/dist/openai/adapter.d.ts +29 -5
  92. package/dist/openai/adapter.d.ts.map +1 -1
  93. package/dist/openai/adapter.js +311 -37
  94. package/dist/openai/adapter.js.map +1 -1
  95. package/dist/output-limit.d.ts +14 -2
  96. package/dist/output-limit.d.ts.map +1 -1
  97. package/dist/output-limit.js +39 -10
  98. package/dist/output-limit.js.map +1 -1
  99. package/dist/pause.d.ts +24 -0
  100. package/dist/pause.d.ts.map +1 -0
  101. package/dist/pause.js +38 -0
  102. package/dist/pause.js.map +1 -0
  103. package/dist/pdf-pages.d.ts +32 -2
  104. package/dist/pdf-pages.d.ts.map +1 -1
  105. package/dist/pdf-pages.js +275 -14
  106. package/dist/pdf-pages.js.map +1 -1
  107. package/dist/pdf-pictures.d.ts +30 -3
  108. package/dist/pdf-pictures.d.ts.map +1 -1
  109. package/dist/pdf-pictures.js +50 -8
  110. package/dist/pdf-pictures.js.map +1 -1
  111. package/dist/pdf-work.d.ts +40 -0
  112. package/dist/pdf-work.d.ts.map +1 -0
  113. package/dist/pdf-work.js +734 -0
  114. package/dist/pdf-work.js.map +1 -0
  115. package/dist/plan.d.ts +22 -4
  116. package/dist/plan.d.ts.map +1 -1
  117. package/dist/plan.js +61 -12
  118. package/dist/plan.js.map +1 -1
  119. package/dist/retry.d.ts +23 -1
  120. package/dist/retry.d.ts.map +1 -1
  121. package/dist/retry.js +33 -3
  122. package/dist/retry.js.map +1 -1
  123. package/dist/search.d.ts +8 -2
  124. package/dist/search.d.ts.map +1 -1
  125. package/dist/search.js +60 -10
  126. package/dist/search.js.map +1 -1
  127. package/dist/sse.d.ts +35 -2
  128. package/dist/sse.d.ts.map +1 -1
  129. package/dist/sse.js +145 -31
  130. package/dist/sse.js.map +1 -1
  131. package/dist/stores.d.ts.map +1 -1
  132. package/dist/stores.js +5 -2
  133. package/dist/stores.js.map +1 -1
  134. package/dist/text-index.d.ts +6 -0
  135. package/dist/text-index.d.ts.map +1 -1
  136. package/dist/text-index.js +25 -8
  137. package/dist/text-index.js.map +1 -1
  138. package/dist/text.d.ts +62 -2
  139. package/dist/text.d.ts.map +1 -1
  140. package/dist/text.js +314 -14
  141. package/dist/text.js.map +1 -1
  142. package/dist/tools.d.ts +61 -1
  143. package/dist/tools.d.ts.map +1 -1
  144. package/dist/tools.js +269 -42
  145. package/dist/tools.js.map +1 -1
  146. package/dist/types.d.ts +102 -3
  147. package/dist/types.d.ts.map +1 -1
  148. package/dist/zip-directory.d.ts +43 -0
  149. package/dist/zip-directory.d.ts.map +1 -0
  150. package/dist/zip-directory.js +130 -0
  151. package/dist/zip-directory.js.map +1 -0
  152. package/docs/README.md +288 -0
  153. package/docs/api.md +37 -381
  154. package/docs/configuration.md +28 -558
  155. package/docs/getting-started.md +407 -223
  156. package/docs/guides/anthropic.md +590 -0
  157. package/docs/guides/conversations.md +629 -0
  158. package/docs/guides/costs-and-limits.md +726 -0
  159. package/docs/guides/deployment.md +654 -0
  160. package/docs/guides/errors-and-reliability.md +735 -0
  161. package/docs/guides/explorer-model.md +399 -0
  162. package/docs/guides/openai-compatible.md +602 -0
  163. package/docs/guides/own-adapter-and-loop.md +1169 -0
  164. package/docs/guides/pdfs.md +971 -0
  165. package/docs/guides/storage.md +731 -0
  166. package/docs/guides/testing.md +1199 -0
  167. package/docs/guides/vertex-and-gemini.md +717 -0
  168. package/docs/guides/web-app.md +1589 -0
  169. package/docs/how-it-works.md +1012 -164
  170. package/docs/measurements.md +881 -0
  171. package/docs/publishing.md +274 -46
  172. package/docs/reference/anthropic.md +427 -0
  173. package/docs/reference/ask.md +892 -0
  174. package/docs/reference/errors-and-retries.md +758 -0
  175. package/docs/reference/events.md +993 -0
  176. package/docs/reference/gemini.md +823 -0
  177. package/docs/reference/library.md +1467 -0
  178. package/docs/reference/node.md +528 -0
  179. package/docs/reference/openai.md +385 -0
  180. package/docs/reference/tools.md +883 -0
  181. package/docs/security.md +897 -103
  182. package/docs/troubleshooting.md +1390 -0
  183. package/package.json +2 -2
  184. package/src/analyze.ts +93 -42
  185. package/src/anthropic/adapter.ts +196 -39
  186. package/src/ask.ts +1087 -202
  187. package/src/encoding.ts +850 -0
  188. package/src/errors.ts +17 -0
  189. package/src/events.ts +442 -0
  190. package/src/evidence.ts +5 -2
  191. package/src/extract.ts +602 -62
  192. package/src/gemini/adapter.ts +118 -65
  193. package/src/gemini/chat.ts +28 -4
  194. package/src/gemini/errors.ts +34 -1
  195. package/src/gemini/generate.ts +23 -10
  196. package/src/gemini/index.ts +3 -3
  197. package/src/gemini/sse.ts +1 -1
  198. package/src/http.ts +376 -1
  199. package/src/index.ts +27 -5
  200. package/src/library.ts +459 -85
  201. package/src/map-reduce.ts +252 -51
  202. package/src/model.ts +236 -3
  203. package/src/node/handlers.ts +137 -22
  204. package/src/node/index.ts +2 -0
  205. package/src/node/sse.ts +198 -0
  206. package/src/openai/adapter.ts +306 -38
  207. package/src/output-limit.ts +44 -8
  208. package/src/pause.ts +41 -0
  209. package/src/pdf-pages.ts +268 -15
  210. package/src/pdf-pictures.ts +56 -9
  211. package/src/pdf-work.ts +722 -0
  212. package/src/plan.ts +68 -12
  213. package/src/retry.ts +49 -5
  214. package/src/search.ts +63 -10
  215. package/src/sse.ts +153 -28
  216. package/src/stores.ts +5 -2
  217. package/src/text-index.ts +26 -7
  218. package/src/text.ts +323 -13
  219. package/src/tools.ts +261 -42
  220. package/src/types.ts +107 -4
  221. package/src/zip-directory.ts +136 -0
package/src/map-reduce.ts CHANGED
@@ -1,7 +1,11 @@
1
- import { withRetry, type RetryOptions } from "./retry.js";
1
+ import { safeErrorMessage } from "./errors.js";
2
+ import { until } from "./http.js";
3
+ import { classifyModelError, errorKindOf, type ModelErrorKind } from "./model.js";
4
+ import { noTextReason } from "./output-limit.js";
5
+ import { statusOf, withRetry, type RetryOptions } from "./retry.js";
2
6
  import { estimateTokens, jsonBytes } from "./text.js";
3
7
  import { numberLines, scanSource, SearchableDocument, type DocumentSource, type TextChunk } from "./search.js";
4
- import type { Budget, GenerateText, ProgressListener } from "./types.js";
8
+ import type { Budget, GenerateText, GenerateUsage, ProgressListener, ToolCallHooks, ToolRequestStart } from "./types.js";
5
9
 
6
10
  const NOTHING = "NOTHING RELEVANT";
7
11
  const PART_OUTPUT_TOKENS = 4_096;
@@ -19,8 +23,123 @@ export type WholeDocumentResult = {
19
23
  truncatedMerges: number;
20
24
  /** The final answer stopped at the output limit. */
21
25
  answerTruncated: boolean;
26
+ /**
27
+ * Why the last step, which writes one answer from the notes, failed. `answer` is then the notes
28
+ * themselves: every part was paid for, and they hold what was found, with line citations.
29
+ */
30
+ answerFailed?: string;
22
31
  };
23
32
 
33
+ /**
34
+ * What went wrong with a model request, by its kind, in words for the model that asked for the
35
+ * read. The request may be a part, a merge of notes, or the last step that writes the answer.
36
+ */
37
+ const FAILED_BECAUSE: Record<ModelErrorKind, string> = {
38
+ context_overflow: "The request was larger than the model takes",
39
+ quota: "The model's quota has run out",
40
+ rate_limit: "The model was busy",
41
+ timeout: "The model took too long to answer",
42
+ unreachable: "The model could not be reached",
43
+ server: "The model failed on its side",
44
+ auth: "The model refused the key or token it was sent",
45
+ invalid: "The model refused the request",
46
+ };
47
+
48
+ const knownKind = (kind: unknown): kind is ModelErrorKind => typeof kind === "string" && Object.hasOwn(FAILED_BECAUSE, kind);
49
+
50
+ /**
51
+ * The HTTP status of a model error: its `status`, or the `statusCode` or `response.status` that
52
+ * the errors of other HTTP clients and SDKs carry (got, http-errors, axios). 0 is a request that
53
+ * got no answer. A number that is no HTTP status is not one.
54
+ */
55
+ function httpStatusOf(error: unknown): number | undefined {
56
+ const other = error as { statusCode?: unknown; response?: { status?: unknown } | null } | null | undefined;
57
+ for (const status of [statusOf(error), other?.statusCode, other?.response?.status]) {
58
+ if (typeof status === "number" && Number.isInteger(status) && (status === 0 || (status >= 100 && status <= 599))) return status;
59
+ }
60
+ return undefined;
61
+ }
62
+
63
+ /**
64
+ * The codes of a connection that failed, Node's and undici's, and their kind. An answer that did
65
+ * not come in time is a timeout.
66
+ */
67
+ const CONNECTION_FAILURES: Record<string, ModelErrorKind> = {
68
+ ECONNREFUSED: "unreachable",
69
+ ECONNRESET: "unreachable",
70
+ ECONNABORTED: "unreachable",
71
+ ENOTFOUND: "unreachable",
72
+ EAI_AGAIN: "unreachable",
73
+ ETIMEDOUT: "unreachable",
74
+ EHOSTUNREACH: "unreachable",
75
+ ENETUNREACH: "unreachable",
76
+ ENETDOWN: "unreachable",
77
+ EPIPE: "unreachable",
78
+ UND_ERR_CONNECT_TIMEOUT: "unreachable",
79
+ UND_ERR_SOCKET: "unreachable",
80
+ UND_ERR_CLOSED: "unreachable",
81
+ UND_ERR_DESTROYED: "unreachable",
82
+ UND_ERR_HEADERS_TIMEOUT: "timeout",
83
+ UND_ERR_BODY_TIMEOUT: "timeout",
84
+ };
85
+
86
+ /**
87
+ * The kind of a connection that failed, from the code of the error or of one that caused it (the
88
+ * `fetch failed` of undici). An `AbortSignal.timeout` of the app's (a `TimeoutError`) is a timeout.
89
+ * Undefined for any other error.
90
+ */
91
+ function connectionFailure(error: unknown): ModelErrorKind | undefined {
92
+ let at = error;
93
+ for (let depth = 0; depth < 4 && typeof at === "object" && at !== null; depth++) {
94
+ const { code, name, cause } = at as { code?: unknown; name?: unknown; cause?: unknown };
95
+ if (typeof code === "string" && Object.hasOwn(CONNECTION_FAILURES, code)) return CONNECTION_FAILURES[code];
96
+ if (name === "TimeoutError") return "timeout";
97
+ at = cause;
98
+ }
99
+ return undefined;
100
+ }
101
+
102
+ /** A reason a provider gives for a reply with no text that is a plain word ("SAFETY", "content_filter"). */
103
+ const PLAIN_REASON = /^[A-Za-z_]{1,40}$/;
104
+
105
+ /**
106
+ * Why a model request of a whole-file read failed, as the model and `onStep` are told: by its
107
+ * kind, its HTTP status, or the code of a connection that failed, never by its message. The
108
+ * provider's message, or the HTTP client's, can name a project, a host, a key or a URL of the
109
+ * server, and goes to the log of the app, not to the model. An error with an HTTP status and no
110
+ * kind (that of a provider's SDK, in a `generate` of the app's own) has its kind told from its
111
+ * status and message. An error with none of these is told as a request that failed. A reply with
112
+ * no text to a part reader of the package's is told in the package's words, as before.
113
+ */
114
+ export function modelFailureReason(error: unknown): string {
115
+ try {
116
+ const noText = noTextReason(error);
117
+ if (noText !== undefined) return `The model returned no text${PLAIN_REASON.test(noText) ? ` (${noText})` : ""}.`;
118
+ const status = httpStatusOf(error);
119
+ let kind: unknown = errorKindOf(error);
120
+ if (!knownKind(kind) && status !== undefined && (status === 0 || status >= 400)) {
121
+ const code = (error as { code?: unknown } | null)?.code;
122
+ kind = classifyModelError(status, error instanceof Error ? error.message : "", { code: typeof code === "string" ? code : undefined }).kind;
123
+ }
124
+ if (!knownKind(kind)) kind = connectionFailure(error);
125
+ if (!knownKind(kind)) return `The model request failed${status ? ` (HTTP ${status})` : ""}.`;
126
+ // A reply that came with a status of success, and could not be read (a gateway's page).
127
+ if (kind === "invalid" && status !== undefined && status >= 200 && status < 300) return `The model's reply could not be read (HTTP ${status}).`;
128
+ return `${FAILED_BECAUSE[kind]}${status ? ` (HTTP ${status})` : ""}.`;
129
+ } catch {
130
+ // An error whose fields throw when read (a getter, a proxy): their words are not told either.
131
+ return "The model request failed.";
132
+ }
133
+ }
134
+
135
+ /** A whole-document read in which no part could be read: nothing was learned, and nothing is returned. */
136
+ export class NothingReadError extends Error {
137
+ constructor(name: string, readonly reason: string) {
138
+ super(`Could not read any part of ${name}: ${reason}`);
139
+ this.name = "NothingReadError";
140
+ }
141
+ }
142
+
24
143
  type Parts = Array<{ from: number; to: number }>;
25
144
 
26
145
  /**
@@ -123,23 +242,52 @@ export class TooManyPartsError extends Error {
123
242
  }
124
243
  }
125
244
 
245
+ /** Two reports of usage as one. */
246
+ function addUsage(sum: GenerateUsage | undefined, used: GenerateUsage): GenerateUsage {
247
+ const out: GenerateUsage = { ...sum };
248
+ for (const key of ["inputTokens", "cachedInputTokens", "outputTokens", "thoughtTokens"] as const) {
249
+ if (typeof used[key] === "number") out[key] = (out[key] ?? 0) + used[key];
250
+ }
251
+ return out;
252
+ }
253
+
254
+ /** Who is told of each model request of a read (`ToolCallHooks.onRequest`), and what the request is. */
255
+ type Told = { onRequest: NonNullable<ToolCallHooks["onRequest"]>; start: ToolRequestStart };
256
+
126
257
  /**
127
258
  * One model call. A model that was busy or failed on its side (an error with an HTTP status worth
128
259
  * retrying) is asked again after a wait, a few times; a request it refused is not. An error that
129
260
  * 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.
261
+ * was kept hit the output limit. When the signal aborts, the call ends with its reason, whether or
262
+ * not the part reader stops. `told` hears when the request starts, each retry, and how it ended,
263
+ * with the usage its part reader reported.
131
264
  */
132
265
  async function ask(
133
266
  generate: GenerateText,
134
267
  request: { system: string; prompt: string; maxOutputTokens: number },
135
268
  signal: AbortSignal | undefined,
136
269
  retry: RetryOptions | undefined,
270
+ told?: Told,
137
271
  ): Promise<{ text: string; truncated: boolean }> {
138
272
  let truncated = false;
139
- const text = await withRetry(() => {
140
- truncated = false;
141
- return generate({ ...request, ...(signal ? { signal } : {}), onTruncated: () => { truncated = true; } });
142
- }, { retry, signal, unknownErrors: "once" });
273
+ const handle = told?.onRequest(told.start);
274
+ let usage: GenerateUsage | undefined;
275
+ const onUsage = handle && ((used: GenerateUsage) => {
276
+ usage = addUsage(usage, used);
277
+ });
278
+ let text: string;
279
+ try {
280
+ text = await withRetry(() => {
281
+ truncated = false;
282
+ // Nothing is sent once the read was stopped: the signal may abort while a part's lines are read.
283
+ signal?.throwIfAborted();
284
+ return until(generate({ ...request, ...(signal ? { signal } : {}), onTruncated: () => { truncated = true; }, ...(onUsage ? { onUsage } : {}) }), signal);
285
+ }, { retry, signal, unknownErrors: "once", ...(handle ? { onRetry: (notice) => handle.retry(notice) } : {}) });
286
+ } catch (error) {
287
+ handle?.end({ outcome: "error", ...(usage ? { usage } : {}), error });
288
+ throw error;
289
+ }
290
+ handle?.end({ outcome: "ok", ...(usage ? { usage } : {}) });
143
291
  return { text: text.trim(), truncated };
144
292
  }
145
293
 
@@ -153,12 +301,21 @@ export async function analyzeWholeDocument(options: {
153
301
  generate: GenerateText;
154
302
  budget: Budget;
155
303
  onProgress?: ProgressListener;
304
+ /** Told of each model request of the read as it starts: see `ToolCallHooks.onRequest`. */
305
+ onRequest?: ToolCallHooks["onRequest"];
156
306
  signal?: AbortSignal;
157
307
  concurrency?: number;
158
308
  /** How a model request that failed is sent again. See `RetryOptions`. */
159
309
  retry?: RetryOptions;
310
+ /**
311
+ * The most model requests this read may make, when the question has a ceiling. A part read as two
312
+ * halves takes one more than planned: it is halved only while this allows it.
313
+ */
314
+ maxRequests?: number;
160
315
  }): Promise<WholeDocumentResult> {
161
- const { document, task, generate, budget, onProgress, signal, retry } = options;
316
+ const { document, task, generate, budget, onProgress, onRequest, signal, retry } = options;
317
+ /** What `ask` tells of a request of this read, when anyone listens. */
318
+ const told = (purpose: ToolRequestStart["purpose"], detail: string): Told | undefined => (onRequest ? { onRequest, start: { purpose, detail } } : undefined);
162
319
  const name = document.meta.name;
163
320
  const parts = await partsOf(document, budget, signal);
164
321
  if (parts.length > budget.maxMapChunks) throw new TooManyPartsError(name, parts.length, budget.maxMapChunks);
@@ -166,19 +323,51 @@ export async function analyzeWholeDocument(options: {
166
323
  let done = 0;
167
324
  let failed = 0;
168
325
  let firstFailure = "";
326
+ let firstError: unknown;
327
+ /** Parts whose text was read and sent to the model: with none, no model request was made. */
328
+ let sent = 0;
169
329
  let truncatedParts = 0;
170
- const notes = await pool(parts.length, options.concurrency ?? 4, async (index) => {
171
- const { from, to } = parts[index]!;
172
- let text: string;
173
- let read = true;
330
+ type Note = { from: number; to: number; text: string; read: boolean };
331
+ /**
332
+ * Parts that may be read as two halves. Each takes one request more than planned, and makes one
333
+ * part more: the parts stay within `maxMapChunks`, and the requests (the parts, a merge, the
334
+ * answer) within `maxRequests`.
335
+ */
336
+ let halvings = Math.max(0, Math.min(
337
+ budget.maxMapChunks - parts.length,
338
+ options.maxRequests === undefined ? Number.POSITIVE_INFINITY : options.maxRequests - parts.length - 2,
339
+ ));
340
+ /** The note on a part that could not be read, and why. */
341
+ const failedPart = (from: number, to: number, error: unknown, reason: string): Note[] => {
342
+ failed++;
343
+ if (!firstFailure) {
344
+ firstFailure = reason;
345
+ firstError = error;
346
+ }
347
+ return [{ from, to, text: `[This part could not be read: ${reason}]`, read: false }];
348
+ };
349
+ /**
350
+ * The notes on one part. A part the model refuses as larger than it takes (its window is smaller
351
+ * than the budget says) is read as two halves instead, once: a half that is still too large is
352
+ * reported as a part that could not be read.
353
+ */
354
+ const readPart = async (from: number, to: number, where: string, halved: boolean, detail: string): Promise<Note[]> => {
355
+ let part: string;
356
+ try {
357
+ part = numberLines(await document.readLines(from, to), from);
358
+ } catch (error) {
359
+ if (signal?.aborted) throw error;
360
+ // The store's error, not the model's: a `DocumentStoreError` tells it in words safe to show.
361
+ return failedPart(from, to, error, safeErrorMessage(error));
362
+ }
363
+ sent++;
174
364
  try {
175
- const part = numberLines(await document.readLines(from, to), from);
176
365
  const reply = await ask(generate, {
177
366
  system: "You read one part of a larger document and take notes for a later step that combines the notes from every part.",
178
367
  prompt: [
179
368
  `Task: ${task}`,
180
369
  "",
181
- `Document: ${name}, part ${index + 1} of ${parts.length}, lines ${from}-${to}.`,
370
+ `Document: ${name}, ${where}, lines ${from}-${to}.`,
182
371
  `Write concise notes on everything in this part that is relevant to the task. Keep exact names, numbers, and quotes that matter. Cite line numbers like (L123). If nothing in this part is relevant, reply exactly: ${NOTHING}`,
183
372
  "",
184
373
  "<part>",
@@ -186,34 +375,46 @@ export async function analyzeWholeDocument(options: {
186
375
  "</part>",
187
376
  ].join("\n"),
188
377
  maxOutputTokens: PART_OUTPUT_TOKENS,
189
- }, signal, retry);
190
- text = reply.text;
378
+ }, signal, retry, told("part", detail));
379
+ let text = reply.text;
191
380
  if (reply.truncated) {
192
381
  truncatedParts++;
193
- text += "\n[These notes were cut off at the output limit. This part has more relevant content than is listed here.]";
382
+ text += "\n[These notes were cut off before their end, at the output limit or by the provider. This part has more relevant content than is listed here.]";
194
383
  }
384
+ return [{ from, to, text, read: true }];
195
385
  } catch (error) {
196
386
  if (signal?.aborted) throw error;
197
- failed++;
198
- read = false;
199
- const reason = error instanceof Error ? error.message : String(error);
200
- firstFailure ||= reason;
201
- text = `[This part could not be read: ${reason}]`;
387
+ if (!halved && to > from && errorKindOf(error) === "context_overflow" && halvings > 0) {
388
+ halvings--;
389
+ const middle = Math.floor((from + to) / 2);
390
+ return [
391
+ ...await readPart(from, middle, `${where}, first half`, true, `first half of ${detail}`),
392
+ ...await readPart(middle + 1, to, `${where}, second half`, true, `second half of ${detail}`),
393
+ ];
394
+ }
395
+ return failedPart(from, to, error, modelFailureReason(error));
202
396
  }
397
+ };
398
+ const notes = (await pool(parts.length, options.concurrency ?? 4, async (index) => {
399
+ const { from, to } = parts[index]!;
400
+ const where = `part ${index + 1} of ${parts.length}`;
401
+ const read = await readPart(from, to, where, false, where);
203
402
  done++;
204
403
  onProgress?.({ kind: "map", message: `Reading ${name}: part ${done} of ${parts.length}`, done, total: parts.length });
205
- return { from, to, text, read };
206
- }, signal);
404
+ return read;
405
+ }, signal)).flat();
207
406
 
208
- // Nothing was read at all: an answer written from here would be invented.
209
- if (failed === parts.length) throw new Error(`Could not read any part of ${name}: ${firstFailure}`);
407
+ // Nothing was read at all: an answer written from here would be invented. When not one part
408
+ // could even be read from the store, no model request was made: that is the store's failure,
409
+ // and the read can be asked for again.
410
+ if (failed === notes.length) throw sent === 0 && firstError !== undefined ? firstError : new NothingReadError(name, firstFailure);
210
411
 
211
412
  const relevant = notes.filter((note) => !saysNothingRelevant(note.text));
212
413
  const relevantParts = relevant.filter((note) => note.read).length;
213
414
  if (relevantParts === 0) {
214
415
  return {
215
- answer: `No part of ${name} contained anything relevant to: ${task}${failed ? ` (${failed} of ${parts.length} parts could not be read.)` : ""}`,
216
- parts: parts.length,
416
+ answer: `No part of ${name} contained anything relevant to: ${task}${failed ? ` (${failed} of ${notes.length} parts could not be read.)` : ""}`,
417
+ parts: notes.length,
217
418
  relevantParts: 0,
218
419
  failedParts: failed,
219
420
  truncatedParts,
@@ -258,7 +459,7 @@ export async function analyzeWholeDocument(options: {
258
459
  system: "You merge partial notes about a document into shorter notes, keeping every relevant fact and line citation.",
259
460
  prompt: `Task: ${task}\n\nMerge these notes from ${name} into one set of notes. Keep line citations.\n\n${batch}`,
260
461
  maxOutputTokens: PART_OUTPUT_TOKENS,
261
- }, signal, retry);
462
+ }, signal, retry, told("merge", `round ${round}: ${index + 1} of ${batches.length}`));
262
463
  if (reply.truncated) truncatedMerges++;
263
464
  merged = reply.truncated ? `${reply.text}\n[These merged notes were cut off at the output limit.]` : reply.text;
264
465
  } catch (error) {
@@ -277,26 +478,26 @@ export async function analyzeWholeDocument(options: {
277
478
 
278
479
  onProgress?.({ kind: "reduce", message: `Writing the answer from ${relevantParts} relevant parts of ${name}`, done: 0, total: 1 });
279
480
  const cutShort = truncatedParts + truncatedMerges;
280
- const final = await ask(generate, {
281
- system: "You write a complete answer from notes taken across every part of a document.",
282
- prompt: [
283
- `Task: ${task}`,
284
- "",
285
- `These notes cover all ${parts.length} parts of ${name}${failed ? ` (${failed} part(s) could not be read)` : ""}. Parts with nothing relevant are omitted.`,
286
- ...(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.`] : []),
287
- "Write one complete answer to the task from them. Keep line citations. Point out contradictions or gaps.",
288
- "",
289
- layer.join("\n\n"),
290
- ].join("\n"),
291
- maxOutputTokens: FINAL_OUTPUT_TOKENS,
292
- }, signal, retry);
293
- return {
294
- answer: final.text,
295
- parts: parts.length,
296
- relevantParts,
297
- failedParts: failed,
298
- truncatedParts,
299
- truncatedMerges,
300
- answerTruncated: final.truncated,
301
- };
481
+ const counts = { parts: notes.length, relevantParts, failedParts: failed, truncatedParts, truncatedMerges };
482
+ let final: { text: string; truncated: boolean };
483
+ try {
484
+ final = await ask(generate, {
485
+ system: "You write a complete answer from notes taken across every part of a document.",
486
+ prompt: [
487
+ `Task: ${task}`,
488
+ "",
489
+ `These notes cover all ${notes.length} parts of ${name}${failed ? ` (${failed} part(s) could not be read)` : ""}. Parts with nothing relevant are omitted.`,
490
+ ...(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.`] : []),
491
+ "Write one complete answer to the task from them. Keep line citations. Point out contradictions or gaps.",
492
+ "",
493
+ layer.join("\n\n"),
494
+ ].join("\n"),
495
+ maxOutputTokens: FINAL_OUTPUT_TOKENS,
496
+ }, signal, retry, told("final", "the answer"));
497
+ } catch (error) {
498
+ if (signal?.aborted) throw error;
499
+ // The notes of every part were paid for and hold what was found: they are the answer, rather than an error.
500
+ return { answer: layer.join("\n\n"), ...counts, answerTruncated: false, answerFailed: modelFailureReason(error) };
501
+ }
502
+ return { answer: final.text, ...counts, answerTruncated: final.truncated };
302
503
  }