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/text.ts CHANGED
@@ -41,6 +41,10 @@ export function foldCase(text: string): string {
41
41
  return out;
42
42
  }
43
43
 
44
+ /** The first and the second half of a character outside the basic plane, as JavaScript holds it. */
45
+ const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;
46
+ const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
47
+
44
48
  /**
45
49
  * Splits lines longer than `limit`, preferring a break after whitespace or punctuation near the
46
50
  * end of each piece. Minified JSON or a PDF paragraph becomes many addressable lines.
@@ -59,7 +63,10 @@ export function wrapLongLines(text: string, limit = MAX_LINE_CHARACTERS): { text
59
63
  while (rest.length > limit) {
60
64
  const window = rest.slice(0, limit);
61
65
  const soft = Math.max(window.lastIndexOf(" "), window.lastIndexOf(","), window.lastIndexOf(";"), window.lastIndexOf("}"));
62
- const cut = soft > limit * 0.8 ? soft + 1 : limit;
66
+ let cut = soft > limit * 0.8 ? soft + 1 : limit;
67
+ // Never between the two halves of a character outside the basic plane (an emoji): each half
68
+ // alone is stored as a replacement character.
69
+ if (isHighSurrogate(rest.charCodeAt(cut - 1)) && isLowSurrogate(rest.charCodeAt(cut))) cut--;
63
70
  out.push(rest.slice(0, cut));
64
71
  rest = rest.slice(cut);
65
72
  }
@@ -172,24 +179,44 @@ export function estimateTokens(text: string): number {
172
179
  return Math.ceil(tokens);
173
180
  }
174
181
 
175
- /** UTF-8 byte length without allocating an encoded copy. */
176
- export function utf8Bytes(text: string): number {
177
- let bytes = 0;
182
+ /**
183
+ * The size of a text in one pass: its UTF-8 bytes, and the bytes it takes as a string in a JSON
184
+ * request body, which is what a model connector's request limit counts. JSON writes a quote and a
185
+ * backslash as two characters, a line break or a tab as two, any other control character as six
186
+ * (`\u0007`), and half of a surrogate pair as six: an export full of quotes or tabs grows by a
187
+ * quarter or more, a novel by a hundredth.
188
+ */
189
+ export function textSizes(text: string): { utf8: number; json: number } {
190
+ let utf8 = 0;
191
+ let escapes = 0;
178
192
  for (let index = 0; index < text.length; index++) {
179
193
  const code = text.charCodeAt(index);
180
- if (code < 0x80) bytes += 1;
181
- else if (code < 0x800) bytes += 2;
182
- else if (code >= 0xd800 && code <= 0xdbff) {
183
- bytes += 4;
194
+ if (code < 0x80) {
195
+ utf8 += 1;
196
+ if (code === 0x22 || code === 0x5c) escapes += 1;
197
+ else if (code < 0x20) escapes += code === 0x0a || code === 0x09 || code === 0x0d || code === 0x08 || code === 0x0c ? 1 : 5;
198
+ } else if (code < 0x800) {
199
+ utf8 += 2;
200
+ } else if (isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1))) {
201
+ utf8 += 4;
184
202
  index++;
185
- } else bytes += 3;
203
+ } else {
204
+ utf8 += 3;
205
+ // Half of a pair on its own: three bytes of replacement character as UTF-8, six as \udXXX in JSON.
206
+ if (code >= 0xd800 && code <= 0xdfff) escapes += 3;
207
+ }
186
208
  }
187
- return bytes;
209
+ return { utf8, json: utf8 + escapes + 2 };
210
+ }
211
+
212
+ /** UTF-8 byte length without allocating an encoded copy. */
213
+ export function utf8Bytes(text: string): number {
214
+ return textSizes(text).utf8;
188
215
  }
189
216
 
190
- /** Bytes a string adds to a JSON request body, including escapes for quotes and newlines. */
217
+ /** Bytes a string takes in a JSON request body: its UTF-8 bytes, the escapes JSON adds, and its two quotes. */
191
218
  export function jsonBytes(text: string): number {
192
- return Math.ceil(utf8Bytes(text) * 1.08) + 2;
219
+ return textSizes(text).json;
193
220
  }
194
221
 
195
222
  /** Fast line lookups over one text. Line numbers are 1-based. */
package/src/tools.ts CHANGED
@@ -1,15 +1,32 @@
1
- import { analyzeWholeDocument, partsOf } from "./map-reduce.js";
1
+ import { safeErrorMessage } from "./errors.js";
2
+ import { analyzeWholeDocument, TooManyPartsError } from "./map-reduce.js";
2
3
  import { cutPdfPages } from "./pdf-pages.js";
3
- import { grepSource, numberLines, rankSource, type DocumentSource } from "./search.js";
4
- import { formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
5
- import type { Budget, GenerateText, ProgressListener, ToolDeclaration, ToolFileLimits, ToolOutput, ToolResult, ToolSet } from "./types.js";
4
+ import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource } from "./search.js";
5
+ import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
6
+ import type { RetryOptions } from "./retry.js";
7
+ import type { Budget, GenerateText, ProgressListener, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
6
8
 
7
9
  const DEFAULT_READ_LINES = 200;
8
10
  const MAX_READ_LINES = 600;
9
11
  /** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
10
12
  export const MAX_VIEW_PAGES = 5;
13
+ /**
14
+ * The time the regex searches of one tool set (one question, in `askGemini`) may take together,
15
+ * unless `regexBudgetMs` says otherwise. An ordinary search of a 60 MB log takes about 0.15 s.
16
+ */
17
+ export const REGEX_BUDGET_MS = 6_000;
11
18
  /** Below this, no page fits: a cut of one page of plain text is larger. */
12
19
  const MIN_FILE_BYTES = 1_024;
20
+ /** The answer of a whole-document read may be this long, when the cap on tool results is lower. */
21
+ const ANALYSIS_RESULT_CHARACTERS = 40_000;
22
+ /** A result is never cut below this, whatever room a caller names: less holds no line of a file. */
23
+ const LEAST_RESULT_CHARACTERS = 600;
24
+ /**
25
+ * How many times one document is read whole by the tools of one tool set (one question, in
26
+ * `askWithFiles`), unless `maxWholeDocumentReads` says otherwise. One read of a large file is
27
+ * up to `maxMapChunks` model requests.
28
+ */
29
+ export const MAX_WHOLE_DOCUMENT_READS = 1;
13
30
 
14
31
  export const TOOL_NAMES = {
15
32
  search: "search_document",
@@ -161,6 +178,17 @@ export function createDocumentTools(options: {
161
178
  generate?: GenerateText;
162
179
  onProgress?: ProgressListener;
163
180
  signal?: AbortSignal;
181
+ /** The most time, in milliseconds, that the regex searches of this tool set may take together. Defaults to `REGEX_BUDGET_MS`. */
182
+ regexBudgetMs?: number;
183
+ /** How many times each document may be read whole by this tool set. Defaults to `MAX_WHOLE_DOCUMENT_READS`. */
184
+ maxWholeDocumentReads?: number;
185
+ /** How a model request of a whole-document read that failed is sent again. */
186
+ retry?: RetryOptions;
187
+ /**
188
+ * False when every document is too large for a whole-document read: `analyze_whole_document` is
189
+ * then not declared. A call of it still answers with the reason. Defaults to true.
190
+ */
191
+ wholeReads?: boolean;
164
192
  /**
165
193
  * PDFs whose pages `view_pages` may show. The tool is declared only when there is at least one
166
194
  * and `loadOriginal` is given. They need not be among `documentIds`: a PDF whose text is in the
@@ -176,11 +204,33 @@ export function createDocumentTools(options: {
176
204
  // The text tools are left out only when there are pages to look at and no document to search.
177
205
  const textTools = allowed.size > 0 || viewable.size === 0;
178
206
  const declarations = [
179
- ...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.generate ? [DECLARATIONS.analyze] : [])] : []),
207
+ ...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
180
208
  ...(viewable.size > 0 ? [DECLARATIONS.view] : []),
181
209
  ];
182
210
  const known = new Set(declarations.map((declaration) => declaration.name));
183
- const limit = options.budget.toolResultCharacters;
211
+ // Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
212
+ if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
213
+ const cap = options.budget.toolResultCharacters;
214
+ /** The cap on the result of one call: the tool set's own, or the room its caller has left when that is less. */
215
+ const limitOf = (limits: ToolCallLimits, own = cap): number => {
216
+ const room = limits.maxResultCharacters;
217
+ return typeof room === "number" && Number.isFinite(room) ? Math.max(LEAST_RESULT_CHARACTERS, Math.min(own, Math.trunc(room))) : own;
218
+ };
219
+ // The model writes the regex, and a file it reads can ask for a slow one: the time is counted
220
+ // over every search of this tool set, not only within one.
221
+ const regexBudget = Math.max(0, options.regexBudgetMs ?? REGEX_BUDGET_MS);
222
+ const regexClock = { usedMs: 0 };
223
+ // Calls of one turn may run together. Regex searches still take their turns, one after another:
224
+ // each must know how much of the time the ones before it used.
225
+ let regexQueue: Promise<unknown> = Promise.resolve();
226
+ const inRegexTurn = <T>(run: () => Promise<T>): Promise<T> => {
227
+ const next = regexQueue.then(run, run);
228
+ regexQueue = next.catch(() => undefined);
229
+ return next;
230
+ };
231
+ const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
232
+ /** Whole-document reads started, by document. */
233
+ const wholeReads = new Map<string, number>();
184
234
  // When no limit is given with a call: three eighths of a request, so that two looks still fit.
185
235
  const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
186
236
 
@@ -194,8 +244,9 @@ export function createDocumentTools(options: {
194
244
  return document;
195
245
  }
196
246
 
197
- const handlers: Record<string, (args: Record<string, unknown>) => Promise<ToolResult>> = {
198
- async [TOOL_NAMES.search](args) {
247
+ const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits) => Promise<ToolResult>> = {
248
+ async [TOOL_NAMES.search](args, limits) {
249
+ const limit = limitOf(limits);
199
250
  const document = await documentFor(args);
200
251
  const query = text(args.query, "query");
201
252
  const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
@@ -221,13 +272,22 @@ export function createDocumentTools(options: {
221
272
  ...(ranked.length === 0 ? { note: "No passage contains these keywords. Try other words, synonyms, or exact mode." } : {}),
222
273
  }, "passages", limit);
223
274
  }
224
- const result = await grepSource(document, query, {
225
- regex: mode === "regex",
226
- caseSensitive: args.case_sensitive === true,
227
- maxResults: integer(args.max_results, 20, 1, 50),
228
- contextLines: integer(args.context_lines, 0, 0, 5),
229
- ...(options.signal ? { signal: options.signal } : {}),
230
- });
275
+ const regex = mode === "regex";
276
+ const grep = async () => {
277
+ const regexLeft = regexBudget - regexClock.usedMs;
278
+ if (regex && regexLeft <= 0) {
279
+ throw new Error("The time for regex searches is used up for this answer. Search with mode \"exact\" or \"keywords\" instead.");
280
+ }
281
+ return grepSource(document, query, {
282
+ regex,
283
+ caseSensitive: args.case_sensitive === true,
284
+ maxResults: integer(args.max_results, 20, 1, 50),
285
+ contextLines: integer(args.context_lines, 0, 0, 5),
286
+ ...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
287
+ ...(options.signal ? { signal: options.signal } : {}),
288
+ });
289
+ };
290
+ const result = await (regex ? inRegexTurn(grep) : grep());
231
291
  return fit({
232
292
  document: document.meta.name,
233
293
  mode,
@@ -240,7 +300,8 @@ export function createDocumentTools(options: {
240
300
  }, "matches", limit);
241
301
  },
242
302
 
243
- async [TOOL_NAMES.read](args) {
303
+ async [TOOL_NAMES.read](args, limits) {
304
+ const limit = limitOf(limits);
244
305
  const document = await documentFor(args);
245
306
  const total = document.lineCount;
246
307
  const start = integer(args.start_line, 1, 1, total);
@@ -249,7 +310,9 @@ export function createDocumentTools(options: {
249
310
  const read = await document.readLines(start, end);
250
311
  let to = end;
251
312
  let body = numberLines(read, start);
252
- while (body.length > limit - 500 && to > start) {
313
+ // The limit is on the result as it is sent, as JSON: quotes, tabs and line breaks each take two characters there.
314
+ const fits = (text: string) => JSON.stringify(text).length <= limit - 500;
315
+ while (!fits(body) && to > start) {
253
316
  to = start + Math.max(0, Math.floor((to - start) * 0.7));
254
317
  body = numberLines(read.slice(0, to - start + 1), start);
255
318
  }
@@ -259,16 +322,20 @@ export function createDocumentTools(options: {
259
322
  lines: `${start}-${to}`,
260
323
  ...(pages ? { pages } : {}),
261
324
  total_lines: total,
262
- text: body.slice(0, limit - 500),
325
+ text: fits(body) ? body : body.slice(0, Math.floor((limit - 500) / 2)),
263
326
  ...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
264
327
  };
265
328
  },
266
329
 
267
- async [TOOL_NAMES.overview](args) {
330
+ async [TOOL_NAMES.overview](args, limits) {
331
+ const limit = limitOf(limits);
268
332
  const document = await documentFor(args);
269
333
  const { meta, lineCount } = document;
270
334
  const tail = Math.max(1, lineCount - 19);
271
- const parts = await partsOf(document, options.budget, options.signal);
335
+ // Counting the parts means reading the whole text, for a number that only says how costly a
336
+ // whole-document read is. It is worked out from the metadata instead, to within a part or
337
+ // two; the read itself counts them.
338
+ const parts = estimateParts(meta, options.budget);
272
339
  const first = Math.min(30, lineCount);
273
340
  return fit({
274
341
  document: meta.name,
@@ -277,7 +344,8 @@ export function createDocumentTools(options: {
277
344
  lines: meta.lines,
278
345
  estimated_tokens: meta.estimatedTokens,
279
346
  ...(meta.pages ? { pages: meta.pages } : {}),
280
- parts_for_whole_document_analysis: parts.length,
347
+ parts_for_whole_document_analysis: parts,
348
+ ...(parts > options.budget.maxMapChunks ? { whole_document_analysis: `Not available for this file: it would take about ${parts} parts, and the limit is ${options.budget.maxMapChunks}. Use search_document and read_document.` } : {}),
281
349
  ...(meta.logProfile ? { log_profile: meta.logProfile } : {}),
282
350
  first_lines: numberLines(await document.readLines(1, first), 1),
283
351
  last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
@@ -285,18 +353,37 @@ export function createDocumentTools(options: {
285
353
  }, "outline", limit);
286
354
  },
287
355
 
288
- async [TOOL_NAMES.analyze](args) {
356
+ async [TOOL_NAMES.analyze](args, limits) {
289
357
  if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
290
358
  const document = await documentFor(args);
291
359
  const task = text(args.task, "task");
292
- const result = await analyzeWholeDocument({
293
- document,
294
- task,
295
- generate: options.generate,
296
- budget: options.budget,
297
- onProgress: options.onProgress,
298
- signal: options.signal,
299
- });
360
+ // A read of the whole file is many model requests. A model that asks for it again, with the
361
+ // task put another way, is told to use what it has. The count is taken before the read
362
+ // starts, so that two calls in one turn do not both pass.
363
+ const id = document.meta.id;
364
+ const reads = wholeReads.get(id) ?? 0;
365
+ if (reads >= maxWholeReads) {
366
+ throw new Error(maxWholeReads === 0
367
+ ? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
368
+ : `${document.meta.name} was already read whole for this question${maxWholeReads > 1 ? ` ${maxWholeReads} times` : ""}, and is not read whole again. Use the answer of that read, or search_document and read_document for the details.`);
369
+ }
370
+ wholeReads.set(id, reads + 1);
371
+ let result;
372
+ try {
373
+ result = await analyzeWholeDocument({
374
+ document,
375
+ task,
376
+ generate: options.generate,
377
+ budget: options.budget,
378
+ onProgress: options.onProgress,
379
+ signal: options.signal,
380
+ ...(options.retry ? { retry: options.retry } : {}),
381
+ });
382
+ } catch (error) {
383
+ // Refused before any model call: that was no read.
384
+ if (error instanceof TooManyPartsError) wholeReads.set(id, reads);
385
+ throw error;
386
+ }
300
387
  const notesCutShort = result.truncatedParts + result.truncatedMerges;
301
388
  return fit({
302
389
  document: document.meta.name,
@@ -307,12 +394,12 @@ export function createDocumentTools(options: {
307
394
  ...(result.answerTruncated ? { answer_cut_short: true } : {}),
308
395
  ...(notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
309
396
  answer: result.answer,
310
- }, null, Math.max(limit, 40_000));
397
+ }, null, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
311
398
  },
312
399
  };
313
400
 
314
401
  /** `view_pages`: the pages as one small PDF, next to a short JSON result. */
315
- async function viewPages(args: Record<string, unknown>, limits: ToolFileLimits): Promise<ToolOutput> {
402
+ async function viewPages(args: Record<string, unknown>, limits: ToolCallLimits): Promise<ToolOutput> {
316
403
  const id = text(args.document_id, "document_id");
317
404
  // The same scope check as the text tools, on its own list: a PDF can be looked at without
318
405
  // being searchable, and the other way round.
@@ -341,7 +428,7 @@ export function createDocumentTools(options: {
341
428
  try {
342
429
  cut = await cutPdfPages(original, from, Math.min(asked, from + mostPages - 1), maxBytes, total);
343
430
  } catch (error) {
344
- throw new Error(`${file}: ${error instanceof Error ? error.message : String(error)}`);
431
+ throw new Error(`${file}: ${safeErrorMessage(error)}`);
345
432
  }
346
433
  const pages = pageRange(cut.from, cut.to);
347
434
  const shown = cut.to - cut.from + 1;
@@ -360,15 +447,16 @@ export function createDocumentTools(options: {
360
447
  };
361
448
  }
362
449
 
363
- const failure = (error: unknown): ToolResult => ({ error: error instanceof Error ? error.message : String(error) });
450
+ // What a tool could not do goes to the model, and from there to a user's screen: never a server path.
451
+ const failure = (error: unknown): ToolResult => ({ error: safeErrorMessage(error) });
364
452
 
365
- async function execute(name: string, args: Record<string, unknown>): Promise<ToolResult> {
453
+ async function execute(name: string, args: Record<string, unknown>, limits: ToolCallLimits = {}): Promise<ToolResult> {
366
454
  if (!known.has(name)) return { error: `Unknown tool ${name}.` };
367
455
  // The pages are a file, and this method returns only JSON. Saying that pages are attached
368
456
  // with nothing attached would be worse than saying that they could not be shown.
369
457
  if (name === TOOL_NAMES.view) return { error: FILES_NOT_DELIVERED };
370
458
  try {
371
- return await handlers[name]!(args);
459
+ return await handlers[name]!(args, limits);
372
460
  } catch (error) {
373
461
  if (options.signal?.aborted) throw error;
374
462
  return failure(error);
@@ -378,9 +466,10 @@ export function createDocumentTools(options: {
378
466
  return {
379
467
  declarations,
380
468
  has: (name) => known.has(name),
381
- execute,
469
+ execute: (name, args) => execute(name, args),
470
+ resultCharacters: (name) => (name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
382
471
  async executeWithFiles(name, args, limits = {}) {
383
- if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args), files: [] };
472
+ if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args, limits), files: [] };
384
473
  try {
385
474
  return await viewPages(args, limits);
386
475
  } catch (error) {
package/src/types.ts CHANGED
@@ -38,6 +38,11 @@ export type DocumentMeta = {
38
38
  bytes: number;
39
39
  /** UTF-8 size of the extracted text. */
40
40
  textBytes: number;
41
+ /**
42
+ * Bytes the text takes inside a JSON request body, with the escapes JSON adds. Absent on a
43
+ * document ingested before 0.4.1: planning then assumes 8% more than `textBytes`.
44
+ */
45
+ jsonBytes?: number;
41
46
  characters: number;
42
47
  lines: number;
43
48
  estimatedTokens: number;
@@ -167,8 +172,8 @@ export type ToolFile = {
167
172
  /** A tool's JSON result, and the files that belong to it. Most tools return no files. */
168
173
  export type ToolOutput = { result: ToolResult; files: ToolFile[] };
169
174
 
170
- /** What a call that can return files is allowed to use of the request it will be sent in. */
171
- export type ToolFileLimits = {
175
+ /** What one tool call is allowed to use of the request its result will be sent in. */
176
+ export type ToolCallLimits = {
172
177
  /**
173
178
  * The most bytes the files of this call may have together. Give the room left in your request,
174
179
  * times 3/4 when files are sent as base64. Defaults to about a third of `maxRequestBytes`.
@@ -176,7 +181,15 @@ export type ToolFileLimits = {
176
181
  maxFileBytes?: number;
177
182
  /** The most pages this call may show. Lower it as the pages already shown use up your token budget. */
178
183
  maxPages?: number;
184
+ /**
185
+ * The most characters the JSON result of this call may have, when that is less than the tool's
186
+ * own cap (`toolResultCharacters`): the room left in the request. The result is cut to it, and
187
+ * says where to go on.
188
+ */
189
+ maxResultCharacters?: number;
179
190
  };
191
+ /** The name of `ToolCallLimits` before 0.5.0. */
192
+ export type ToolFileLimits = ToolCallLimits;
180
193
 
181
194
  export type ToolSet = {
182
195
  declarations: ToolDeclaration[];
@@ -190,11 +203,19 @@ export type ToolSet = {
190
203
  * Runs a tool call and also returns the files it produced, to be sent to the model with the
191
204
  * result. Use it in place of `execute` in a loop that can send files.
192
205
  */
193
- executeWithFiles(name: string, args: Record<string, unknown>, limits?: ToolFileLimits): Promise<ToolOutput>;
206
+ executeWithFiles(name: string, args: Record<string, unknown>, limits?: ToolCallLimits): Promise<ToolOutput>;
194
207
  /** A short, human-readable line describing a call, for progress UIs. */
195
208
  describe(name: string, args: Record<string, unknown>): string;
209
+ /**
210
+ * The most characters the JSON result of a tool can have: what a loop sets aside in its request
211
+ * before it runs a call.
212
+ */
213
+ resultCharacters(name: string): number;
196
214
  };
197
215
 
216
+ /** Tokens one model request used, as far as the provider said. */
217
+ export type GenerateUsage = { inputTokens?: number; cachedInputTokens?: number; outputTokens?: number; thoughtTokens?: number };
218
+
198
219
  /** A plain text completion. The package stays provider-neutral by taking this as a function. */
199
220
  export type GenerateText = (request: {
200
221
  system: string;
@@ -207,6 +228,11 @@ export type GenerateText = (request: {
207
228
  * as before, without that warning.
208
229
  */
209
230
  onTruncated?: () => void;
231
+ /**
232
+ * Call this once for every request that was answered, with the tokens it used, so that the cost
233
+ * of a whole-document read is counted. Optional: without it those requests are not in the totals.
234
+ */
235
+ onUsage?: (usage: GenerateUsage) => void;
210
236
  }) => Promise<string>;
211
237
 
212
238
  export type ProgressEvent = {