llm-large-files 0.4.1 → 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 (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  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 +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
package/src/map-reduce.ts CHANGED
@@ -1,6 +1,11 @@
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";
1
6
  import { estimateTokens, jsonBytes } from "./text.js";
2
7
  import { numberLines, scanSource, SearchableDocument, type DocumentSource, type TextChunk } from "./search.js";
3
- import type { Budget, GenerateText, ProgressListener } from "./types.js";
8
+ import type { Budget, GenerateText, GenerateUsage, ProgressListener, ToolCallHooks, ToolRequestStart } from "./types.js";
4
9
 
5
10
  const NOTHING = "NOTHING RELEVANT";
6
11
  const PART_OUTPUT_TOKENS = 4_096;
@@ -18,8 +23,123 @@ export type WholeDocumentResult = {
18
23
  truncatedMerges: number;
19
24
  /** The final answer stopped at the output limit. */
20
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;
21
31
  };
22
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
+
23
143
  type Parts = Array<{ from: number; to: number }>;
24
144
 
25
145
  /**
@@ -114,26 +234,60 @@ async function pool<T>(count: number, concurrency: number, run: (index: number)
114
234
  return results;
115
235
  }
116
236
 
117
- async function withRetry(call: () => Promise<string>, signal?: AbortSignal): Promise<string> {
118
- try {
119
- return await call();
120
- } catch (error) {
121
- if (signal?.aborted) throw error;
122
- return call();
237
+ /** A whole-document read that was refused before any model call: the document has too many parts. */
238
+ export class TooManyPartsError extends Error {
239
+ constructor(name: string, readonly parts: number, readonly limit: number) {
240
+ super(`Reading all of ${name} needs ${parts} model calls, over the limit of ${limit}. Use search_document to narrow the question first.`);
241
+ this.name = "TooManyPartsError";
242
+ }
243
+ }
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];
123
250
  }
251
+ return out;
124
252
  }
125
253
 
126
- /** One model call, retried once. `truncated` is true when the reply that was kept hit the output limit. */
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
+
257
+ /**
258
+ * One model call. A model that was busy or failed on its side (an error with an HTTP status worth
259
+ * retrying) is asked again after a wait, a few times; a request it refused is not. An error that
260
+ * says nothing of the kind is tried once more, at once. `truncated` is true when the reply that
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.
264
+ */
127
265
  async function ask(
128
266
  generate: GenerateText,
129
267
  request: { system: string; prompt: string; maxOutputTokens: number },
130
268
  signal: AbortSignal | undefined,
269
+ retry: RetryOptions | undefined,
270
+ told?: Told,
131
271
  ): Promise<{ text: string; truncated: boolean }> {
132
272
  let truncated = false;
133
- const text = await withRetry(() => {
134
- truncated = false;
135
- return generate({ ...request, signal, onTruncated: () => { truncated = true; } });
136
- }, signal);
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 } : {}) });
137
291
  return { text: text.trim(), truncated };
138
292
  }
139
293
 
@@ -147,32 +301,73 @@ export async function analyzeWholeDocument(options: {
147
301
  generate: GenerateText;
148
302
  budget: Budget;
149
303
  onProgress?: ProgressListener;
304
+ /** Told of each model request of the read as it starts: see `ToolCallHooks.onRequest`. */
305
+ onRequest?: ToolCallHooks["onRequest"];
150
306
  signal?: AbortSignal;
151
307
  concurrency?: number;
308
+ /** How a model request that failed is sent again. See `RetryOptions`. */
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;
152
315
  }): Promise<WholeDocumentResult> {
153
- const { document, task, generate, budget, onProgress, signal } = 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);
154
319
  const name = document.meta.name;
155
320
  const parts = await partsOf(document, budget, signal);
156
- if (parts.length > budget.maxMapChunks) {
157
- 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.`);
158
- }
321
+ if (parts.length > budget.maxMapChunks) throw new TooManyPartsError(name, parts.length, budget.maxMapChunks);
159
322
 
160
323
  let done = 0;
161
324
  let failed = 0;
162
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;
163
329
  let truncatedParts = 0;
164
- const notes = await pool(parts.length, options.concurrency ?? 4, async (index) => {
165
- const { from, to } = parts[index]!;
166
- let text: string;
167
- 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++;
168
364
  try {
169
- const part = numberLines(await document.readLines(from, to), from);
170
365
  const reply = await ask(generate, {
171
366
  system: "You read one part of a larger document and take notes for a later step that combines the notes from every part.",
172
367
  prompt: [
173
368
  `Task: ${task}`,
174
369
  "",
175
- `Document: ${name}, part ${index + 1} of ${parts.length}, lines ${from}-${to}.`,
370
+ `Document: ${name}, ${where}, lines ${from}-${to}.`,
176
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}`,
177
372
  "",
178
373
  "<part>",
@@ -180,34 +375,46 @@ export async function analyzeWholeDocument(options: {
180
375
  "</part>",
181
376
  ].join("\n"),
182
377
  maxOutputTokens: PART_OUTPUT_TOKENS,
183
- }, signal);
184
- text = reply.text;
378
+ }, signal, retry, told("part", detail));
379
+ let text = reply.text;
185
380
  if (reply.truncated) {
186
381
  truncatedParts++;
187
- 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.]";
188
383
  }
384
+ return [{ from, to, text, read: true }];
189
385
  } catch (error) {
190
386
  if (signal?.aborted) throw error;
191
- failed++;
192
- read = false;
193
- const reason = error instanceof Error ? error.message : String(error);
194
- firstFailure ||= reason;
195
- 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));
196
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);
197
402
  done++;
198
403
  onProgress?.({ kind: "map", message: `Reading ${name}: part ${done} of ${parts.length}`, done, total: parts.length });
199
- return { from, to, text, read };
200
- }, signal);
404
+ return read;
405
+ }, signal)).flat();
201
406
 
202
- // Nothing was read at all: an answer written from here would be invented.
203
- 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);
204
411
 
205
412
  const relevant = notes.filter((note) => !saysNothingRelevant(note.text));
206
413
  const relevantParts = relevant.filter((note) => note.read).length;
207
414
  if (relevantParts === 0) {
208
415
  return {
209
- answer: `No part of ${name} contained anything relevant to: ${task}${failed ? ` (${failed} of ${parts.length} parts could not be read.)` : ""}`,
210
- 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,
211
418
  relevantParts: 0,
212
419
  failedParts: failed,
213
420
  truncatedParts,
@@ -252,7 +459,7 @@ export async function analyzeWholeDocument(options: {
252
459
  system: "You merge partial notes about a document into shorter notes, keeping every relevant fact and line citation.",
253
460
  prompt: `Task: ${task}\n\nMerge these notes from ${name} into one set of notes. Keep line citations.\n\n${batch}`,
254
461
  maxOutputTokens: PART_OUTPUT_TOKENS,
255
- }, signal);
462
+ }, signal, retry, told("merge", `round ${round}: ${index + 1} of ${batches.length}`));
256
463
  if (reply.truncated) truncatedMerges++;
257
464
  merged = reply.truncated ? `${reply.text}\n[These merged notes were cut off at the output limit.]` : reply.text;
258
465
  } catch (error) {
@@ -271,26 +478,26 @@ export async function analyzeWholeDocument(options: {
271
478
 
272
479
  onProgress?.({ kind: "reduce", message: `Writing the answer from ${relevantParts} relevant parts of ${name}`, done: 0, total: 1 });
273
480
  const cutShort = truncatedParts + truncatedMerges;
274
- const final = await ask(generate, {
275
- system: "You write a complete answer from notes taken across every part of a document.",
276
- prompt: [
277
- `Task: ${task}`,
278
- "",
279
- `These notes cover all ${parts.length} parts of ${name}${failed ? ` (${failed} part(s) could not be read)` : ""}. Parts with nothing relevant are omitted.`,
280
- ...(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.`] : []),
281
- "Write one complete answer to the task from them. Keep line citations. Point out contradictions or gaps.",
282
- "",
283
- layer.join("\n\n"),
284
- ].join("\n"),
285
- maxOutputTokens: FINAL_OUTPUT_TOKENS,
286
- }, signal);
287
- return {
288
- answer: final.text,
289
- parts: parts.length,
290
- relevantParts,
291
- failedParts: failed,
292
- truncatedParts,
293
- truncatedMerges,
294
- answerTruncated: final.truncated,
295
- };
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 };
296
503
  }