llm-large-files 0.9.0 → 0.10.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 (222) hide show
  1. package/CHANGELOG.md +446 -0
  2. package/README.md +13 -7
  3. package/dist/access.d.ts +45 -3
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +106 -3
  6. package/dist/access.js.map +1 -1
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +115 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +572 -103
  26. package/dist/ask.js.map +1 -1
  27. package/dist/citations.d.ts +36 -0
  28. package/dist/citations.d.ts.map +1 -0
  29. package/dist/citations.js +291 -0
  30. package/dist/citations.js.map +1 -0
  31. package/dist/error-info.d.ts +13 -0
  32. package/dist/error-info.d.ts.map +1 -1
  33. package/dist/error-info.js +37 -1
  34. package/dist/error-info.js.map +1 -1
  35. package/dist/errors.d.ts +3 -1
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +3 -1
  38. package/dist/errors.js.map +1 -1
  39. package/dist/events.d.ts +25 -7
  40. package/dist/events.d.ts.map +1 -1
  41. package/dist/events.js.map +1 -1
  42. package/dist/evidence.d.ts.map +1 -1
  43. package/dist/evidence.js +21 -2
  44. package/dist/evidence.js.map +1 -1
  45. package/dist/extract.d.ts.map +1 -1
  46. package/dist/extract.js +6 -1
  47. package/dist/extract.js.map +1 -1
  48. package/dist/gemini/adapter.d.ts +35 -4
  49. package/dist/gemini/adapter.d.ts.map +1 -1
  50. package/dist/gemini/adapter.js +68 -29
  51. package/dist/gemini/adapter.js.map +1 -1
  52. package/dist/gemini/chat.d.ts +28 -55
  53. package/dist/gemini/chat.d.ts.map +1 -1
  54. package/dist/gemini/chat.js +20 -27
  55. package/dist/gemini/chat.js.map +1 -1
  56. package/dist/gemini/endpoints.d.ts +59 -11
  57. package/dist/gemini/endpoints.d.ts.map +1 -1
  58. package/dist/gemini/endpoints.js +33 -7
  59. package/dist/gemini/endpoints.js.map +1 -1
  60. package/dist/gemini/errors.d.ts +39 -5
  61. package/dist/gemini/errors.d.ts.map +1 -1
  62. package/dist/gemini/errors.js +70 -9
  63. package/dist/gemini/errors.js.map +1 -1
  64. package/dist/gemini/generate.d.ts +53 -2
  65. package/dist/gemini/generate.d.ts.map +1 -1
  66. package/dist/gemini/generate.js +100 -50
  67. package/dist/gemini/generate.js.map +1 -1
  68. package/dist/gemini/index.d.ts +3 -3
  69. package/dist/gemini/index.d.ts.map +1 -1
  70. package/dist/http.d.ts +41 -3
  71. package/dist/http.d.ts.map +1 -1
  72. package/dist/http.js +40 -2
  73. package/dist/http.js.map +1 -1
  74. package/dist/index.d.ts +6 -4
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ingest.d.ts +9 -1
  79. package/dist/ingest.d.ts.map +1 -1
  80. package/dist/ingest.js +50 -25
  81. package/dist/ingest.js.map +1 -1
  82. package/dist/library.d.ts +129 -2
  83. package/dist/library.d.ts.map +1 -1
  84. package/dist/library.js +224 -149
  85. package/dist/library.js.map +1 -1
  86. package/dist/map-reduce.d.ts +176 -10
  87. package/dist/map-reduce.d.ts.map +1 -1
  88. package/dist/map-reduce.js +804 -58
  89. package/dist/map-reduce.js.map +1 -1
  90. package/dist/model.d.ts +36 -4
  91. package/dist/model.d.ts.map +1 -1
  92. package/dist/model.js +17 -1
  93. package/dist/model.js.map +1 -1
  94. package/dist/node/handlers.d.ts +29 -8
  95. package/dist/node/handlers.d.ts.map +1 -1
  96. package/dist/node/handlers.js +148 -126
  97. package/dist/node/handlers.js.map +1 -1
  98. package/dist/node/index.d.ts +1 -1
  99. package/dist/node/index.d.ts.map +1 -1
  100. package/dist/node/index.js.map +1 -1
  101. package/dist/node/ingest-child.js +2 -2
  102. package/dist/node/ingest-child.js.map +1 -1
  103. package/dist/node/spool.d.ts +9 -5
  104. package/dist/node/spool.d.ts.map +1 -1
  105. package/dist/node/spool.js +28 -15
  106. package/dist/node/spool.js.map +1 -1
  107. package/dist/node/sse.d.ts +6 -5
  108. package/dist/node/sse.d.ts.map +1 -1
  109. package/dist/node/sse.js +8 -7
  110. package/dist/node/sse.js.map +1 -1
  111. package/dist/openai/adapter.d.ts +5 -1
  112. package/dist/openai/adapter.d.ts.map +1 -1
  113. package/dist/openai/adapter.js +53 -12
  114. package/dist/openai/adapter.js.map +1 -1
  115. package/dist/output-limit.d.ts +2 -1
  116. package/dist/output-limit.d.ts.map +1 -1
  117. package/dist/output-limit.js +5 -2
  118. package/dist/output-limit.js.map +1 -1
  119. package/dist/pdf-outline.d.ts +71 -0
  120. package/dist/pdf-outline.d.ts.map +1 -0
  121. package/dist/pdf-outline.js +414 -0
  122. package/dist/pdf-outline.js.map +1 -0
  123. package/dist/plan.d.ts +137 -7
  124. package/dist/plan.d.ts.map +1 -1
  125. package/dist/plan.js +248 -26
  126. package/dist/plan.js.map +1 -1
  127. package/dist/prepare.d.ts +50 -0
  128. package/dist/prepare.d.ts.map +1 -0
  129. package/dist/prepare.js +207 -0
  130. package/dist/prepare.js.map +1 -0
  131. package/dist/ranged.d.ts +2 -1
  132. package/dist/ranged.d.ts.map +1 -1
  133. package/dist/ranged.js +16 -3
  134. package/dist/ranged.js.map +1 -1
  135. package/dist/search.d.ts +7 -0
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +72 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/stores.d.ts +6 -0
  140. package/dist/stores.d.ts.map +1 -1
  141. package/dist/stores.js +82 -11
  142. package/dist/stores.js.map +1 -1
  143. package/dist/tools.d.ts +22 -2
  144. package/dist/tools.d.ts.map +1 -1
  145. package/dist/tools.js +323 -76
  146. package/dist/tools.js.map +1 -1
  147. package/dist/types.d.ts +49 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/whole-cost.d.ts +37 -0
  150. package/dist/whole-cost.d.ts.map +1 -0
  151. package/dist/whole-cost.js +46 -0
  152. package/dist/whole-cost.js.map +1 -0
  153. package/docs/README.md +4 -0
  154. package/docs/guides/anthropic.md +5 -2
  155. package/docs/guides/conversations.md +1 -1
  156. package/docs/guides/costs-and-limits.md +132 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +157 -45
  159. package/docs/guides/explorer-model.md +4 -1
  160. package/docs/guides/openai-compatible.md +47 -7
  161. package/docs/guides/own-adapter-and-loop.md +33 -6
  162. package/docs/guides/pdfs.md +96 -7
  163. package/docs/guides/storage.md +46 -3
  164. package/docs/guides/testing.md +71 -0
  165. package/docs/guides/vertex-and-gemini.md +159 -50
  166. package/docs/guides/web-app.md +10 -6
  167. package/docs/how-it-works.md +120 -22
  168. package/docs/measurements.md +172 -5
  169. package/docs/publishing.md +76 -4
  170. package/docs/reference/anthropic.md +12 -7
  171. package/docs/reference/ask.md +262 -35
  172. package/docs/reference/errors-and-retries.md +30 -2
  173. package/docs/reference/events.md +27 -10
  174. package/docs/reference/gemini.md +184 -68
  175. package/docs/reference/library.md +190 -23
  176. package/docs/reference/node.md +51 -17
  177. package/docs/reference/openai.md +21 -10
  178. package/docs/reference/tools.md +271 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +472 -0
  182. package/package.json +5 -1
  183. package/src/access.ts +127 -4
  184. package/src/aggregate.ts +92 -14
  185. package/src/analyze.ts +2 -2
  186. package/src/answer-info.ts +45 -0
  187. package/src/anthropic/adapter.ts +40 -11
  188. package/src/ask.ts +646 -106
  189. package/src/citations.ts +294 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +29 -6
  193. package/src/evidence.ts +21 -2
  194. package/src/extract.ts +6 -1
  195. package/src/gemini/adapter.ts +99 -32
  196. package/src/gemini/chat.ts +53 -82
  197. package/src/gemini/endpoints.ts +89 -16
  198. package/src/gemini/errors.ts +74 -11
  199. package/src/gemini/generate.ts +147 -57
  200. package/src/gemini/index.ts +3 -3
  201. package/src/http.ts +65 -4
  202. package/src/index.ts +6 -4
  203. package/src/ingest.ts +58 -27
  204. package/src/library.ts +336 -142
  205. package/src/map-reduce.ts +855 -67
  206. package/src/model.ts +44 -4
  207. package/src/node/handlers.ts +159 -118
  208. package/src/node/index.ts +1 -0
  209. package/src/node/ingest-child.ts +2 -2
  210. package/src/node/spool.ts +28 -14
  211. package/src/node/sse.ts +8 -7
  212. package/src/openai/adapter.ts +56 -13
  213. package/src/output-limit.ts +5 -2
  214. package/src/pdf-outline.ts +400 -0
  215. package/src/plan.ts +287 -36
  216. package/src/prepare.ts +253 -0
  217. package/src/ranged.ts +16 -3
  218. package/src/search.ts +69 -13
  219. package/src/stores.ts +76 -11
  220. package/src/tools.ts +327 -75
  221. package/src/types.ts +45 -1
  222. package/src/whole-cost.ts +64 -0
@@ -266,29 +266,30 @@ is quiet for less: see [Deployment](./deployment.md).
266
266
  ### Part reads have a time limit of their own
267
267
 
268
268
  The waits cover chat requests. Each request of a whole-file read (a part read) has a limit on its
269
- whole time instead: `timeoutMs` of `openAiCompatible()` and `anthropic()`, 180,000 by default. For
270
- Gemini it is 180 s, and neither `gemini()` nor `askGemini` has an option for it. A part read that
271
- runs out of time is tried once more, at once. If it fails again, the tool's result says the part
272
- could not be read (`parts_that_failed`), and the question goes on.
273
-
274
- To give Gemini part reads more time, replace the adapter's `generateText` and call
275
- `askWithFiles`:
269
+ whole time instead: `timeoutMs` of `gemini()`, `askGemini`, `openAiCompatible()` and
270
+ `anthropic()`, 180,000 by default. 0 sets none. A part read that runs out of time is an error of
271
+ kind `timeout` and status 0, in every adapter. It is tried once more, after the first wait of
272
+ `retry` (250 to 500 ms by default). If it fails again, the tool's result says the part could not be
273
+ read (`parts_that_failed`), and the question goes on.
276
274
 
277
275
  ```ts
278
- import { askWithFiles, type ModelAdapter } from "llm-large-files";
279
- import { createGeminiGenerateText, gemini } from "llm-large-files/gemini";
276
+ import { askGemini, gemini } from "llm-large-files/gemini";
280
277
 
281
- const patient: ModelAdapter = {
282
- ...gemini(endpoint),
283
- // Each part read may take 5 minutes.
284
- generateText: createGeminiGenerateText({ url: endpoint.url, headers: endpoint.headers, timeoutMs: 300_000 }),
285
- };
286
- const result = await askWithFiles({ files, model: patient, documentIds, messages, owner });
278
+ // Each part read may take 5 minutes.
279
+ const answer = await askGemini({ files, endpoint, documentIds, messages, owner, timeoutMs: 300_000 });
280
+
281
+ // The same option on an adapter, for askWithFiles.
282
+ const model = gemini(endpoint, { timeoutMs: 300_000 });
287
283
  ```
288
284
 
289
- `analysisConfig` of `gemini()` is `generationConfig` here, if you set one. With an
290
- [explorer model](./explorer-model.md), the part reads are the explorer's: replace its
291
- `generateText`.
285
+ `askGemini`'s `timeoutMs` covers the part reads of both models. With `askWithFiles` and an
286
+ [explorer model](./explorer-model.md), the part reads are the explorer's: set `timeoutMs` on its
287
+ adapter.
288
+
289
+ Before 0.10.0, `gemini()` and `askGemini` had no option for it: a Gemini part read had 180 s. A
290
+ part read that ran out of time threw the timer's abort error, with no status, and was tried once
291
+ more at once. `timeoutMs: 0` of `openAiCompatible()` and `anthropic()` aborted every part read at
292
+ once.
292
293
 
293
294
  ## An overall deadline
294
295
 
@@ -402,8 +403,10 @@ that says what was wrong:
402
403
  `UNEXPECTED_TOOL_CALL`. The step says "The model's tool call could not be read: it was asked to
403
404
  send it again".
404
405
  - **A first reply with nothing in it**: no text and no tool call, before any tool call of the
405
- question was answered, and not cut off at the output limit or stopped by a filter. The step says
406
- "The model's first reply was empty: it was asked again".
406
+ question was answered, and not cut off at the output limit, stopped by a filter, or ended for
407
+ another reason that asking again does not mend (`finish: "other"`: Gemini's `OTHER`,
408
+ `LANGUAGE` and the like, since 0.10.0). The step says "The model's first reply was empty: it was
409
+ asked again".
407
410
 
408
411
  Without the second try, the answer would be written from the document cards alone and look like any
409
412
  other. At most two such second tries are made in a question, and each takes one of
@@ -411,6 +414,10 @@ other. At most two such second tries are made in a question, and each takes one
411
414
  [How it works](../how-it-works.md#empty-or-broken-turns). When the second try is empty too, the
412
415
  loop asks for the answer, as it does at the end of every question.
413
416
 
417
+ A turn whose tool call could not be read is never the answer, even with a remark in it ("Let me
418
+ look at the error lines."): on the last tool turn, or when its second try could not be read either,
419
+ the loop asks for the answer (new in 0.10.0; before, the remark was taken for the answer).
420
+
414
421
  **The answer's second try.** The request for the answer (`toolChoice: "none"`) is asked for once
415
422
  more when its reply has no text: when it is empty, or holds a tool call the model was told not to
416
423
  make (Gemini's `UNEXPECTED_TOOL_CALL` or `MALFORMED_FUNCTION_CALL`, or calls from an adapter of
@@ -419,8 +426,10 @@ called in this reply: write the answer now, in text, from what is above.", and i
419
426
  step says "The model's answer was empty: it was asked again", or "The model called a tool instead
420
427
  of answering: it was asked again for the answer". It is one of the two second tries of the
421
428
  question, and it can be one request past `limits.toolTurns`. It is not made after a refusal, a
422
- filter, or a reply cut off at the output limit with nothing in it, nor once `limits.requests` or
423
- `limits.inputTokens` is reached. When its reply has no text either, `answered` is false.
429
+ filter, another reason that asking again does not mend (`"other"`), or a reply cut off at the
430
+ output limit with nothing in it, nor once `limits.requests` or the ceiling of input tokens is
431
+ reached. When its reply has no text either, `answered` is false. So a reply that Gemini ends with
432
+ `MODEL_ARMOR`, `OTHER` or `LANGUAGE` costs 2 requests, not 4 (once the adapter maps them).
424
433
 
425
434
  A single call that cannot be run is not a broken turn: arguments that are not a JSON object, a call
426
435
  cut off at the output limit, a Claude call whose block never closed. It is answered with an error
@@ -489,6 +498,11 @@ whose parts all failed. The question goes on, and can still be answered. A faile
489
498
  - in `toolTurns`, as a call whose `result.error` is a string;
490
499
  - not in `evidence`, which lists only what was shown.
491
500
 
501
+ A tool call that rejects, instead of answering with an error, ends the question with that error
502
+ (`run.error`): a tool set of your own whose `executeWithFiles` throws, or `onToolResult` when it
503
+ throws. The model gets nothing of it. Since 0.10.0 a question also stops at once when its signal
504
+ aborts while a tool call, or the planning of the documents, waits for a store that does not answer.
505
+
492
506
  A whole-file read tells the model why a model request failed by the error's kind, its HTTP status
493
507
  or the code of a connection that failed, never by the error's words: the provider's message, or an
494
508
  HTTP client's, can name a project, a host, a masked key, or a URL with a key in it. The same words
@@ -530,46 +544,108 @@ for (const call of failed) console.warn(`Tool ${call.name} failed: ${String(call
530
544
 
531
545
  ## When there is no answer: `answered` and `finishReason`
532
546
 
533
- A question can end without an error and without an answer. `answered` is false when the model's
534
- last turn had no text:
547
+ A question can end without an error and without an answer. `answered` is false when the reply that
548
+ should be the answer had no text:
535
549
 
536
550
  - **The provider refused the prompt.** `blockReason` says why: Gemini's `promptFeedback.blockReason`
537
551
  (such as "SAFETY"), "refusal" or "refusal: " and its category for Claude, "content_filter" for an
538
552
  OpenAI-compatible reply that was filtered with nothing in it. Nothing more is asked after it.
539
553
  - **The last reply ended without text**: cut off at the output limit before its first word, stopped
540
554
  by a filter, or an answer with no text (empty, or a tool call) after its one second try.
555
+ - **The answer was filtered, and `filteredAnswer` is `"drop"`** (new in 0.10.0): `text` is `""`.
541
556
 
542
557
  `text` may then be empty, hold only a remark the model wrote before a tool call, or the start of a
543
558
  reply the provider then refused. Show your own message instead.
544
559
 
545
560
  `finishReason` is the provider's own word for how the last chat reply ended: "STOP", "MAX_TOKENS"
546
561
  or "SAFETY" from Gemini, "stop", "length" or "content_filter" from an OpenAI-compatible server,
547
- "end_turn", "max_tokens" or "refusal" from Claude. An answer can be `answered: true` and still be
548
- cut off at the output limit. Tell the user, or raise the model's output limit (`maxOutputTokens` in
549
- Gemini's `generationConfig`, the limit in `body` of `openAiCompatible()`, `maxTokens` of
550
- `anthropic()`). Claude's `model_context_window_exceeded` means its window filled: shorten the chat
551
- rather than raise the output limit.
562
+ "end_turn", "max_tokens" or "refusal" from Claude. Since 0.10.0 `finish` says the same in the
563
+ library's words, the same for every provider: `"complete"`, `"cut"` (the output limit),
564
+ `"filtered"`, `"malformed_call"` or `"other"`. An answer can be `answered: true` and still be cut off
565
+ at the output limit, or stopped by a filter part-way. Tell the user, or raise the model's output
566
+ limit (`maxOutputTokens` in Gemini's `generationConfig`, the limit in `body` of
567
+ `openAiCompatible()`, `maxTokens` of `anthropic()`). Claude's `model_context_window_exceeded` means
568
+ its window filled: shorten the chat rather than raise the output limit.
569
+
570
+ ## Filtered and cut answers
571
+
572
+ New in 0.10.0. A reply that a filter stopped part-way was an answer like any other in 0.9: "The
573
+ employee's medical leave was", with `answered: true`. Now:
574
+
575
+ - **`result.finish`** is the `finish` of the reply whose text is the answer, or of the last reply when
576
+ none answered. Absent when the adapter does not say.
577
+ - **An `answer_filtered` notice** comes when a filter stopped the answer, with or without text, and
578
+ **an `answer_cut` notice** when the answer stopped at the output limit. Both come before
579
+ `run.finish`, with `display: "none"`: no callback of earlier versions gets them.
580
+ - **`filteredAnswer: "drop"`** drops a filtered answer: `answered: false`, `text: ""`. The default,
581
+ `"keep"`, keeps its text, as 0.9 did. A cut answer is kept either way: it is not wrong, only
582
+ short.
583
+
584
+ **Text already streamed cannot be taken back.** With `onText`, `streamText` or `askStream`, the
585
+ filtered reply's text may have reached the page before the filter's word came. Under `"drop"`, the
586
+ `answer_filtered` notice then has `discardText: true`: the page takes away the text it showed for
587
+ the question, and shows your message instead. Text of a reply that was not streamed is never sent
588
+ when it is to be dropped. Earlier remarks of the question (before a tool call) are dropped with it,
589
+ and `discardText` covers them too.
552
590
 
553
591
  ```ts
554
- import type { AskResult } from "llm-large-files";
592
+ import type { AskEvent } from "llm-large-files";
593
+
594
+ /** The answer as the page shows it, from the events of the question as they come. */
595
+ export function answerView(render: (text: string) => void): (event: AskEvent) => void {
596
+ let shown = "";
597
+ return (event) => {
598
+ if (event.type === "text") render((shown += event.delta));
599
+ // A filter stopped the answer, and the server dropped it: take back what was shown.
600
+ if (event.type === "notice" && event.code === "answer_filtered" && event.discardText) render((shown = ""));
601
+ };
602
+ }
603
+ ```
555
604
 
556
- /** The words of the output limit, as each provider says them. */
557
- const CUT_OFF = new Set(["MAX_TOKENS", "length", "max_tokens"]);
605
+ **`answerInfoOf(result)`** gives the reason in one value, as `errorInfoOf` does for errors:
606
+ `complete`, and `reason` one of `"filtered"`, `"cut"`, `"blocked"`, `"language"`, `"no_answer"` or
607
+ `"other"`, with `finish` and the provider's `finishReason`. `"language"` is Gemini's `LANGUAGE`: the
608
+ model does not take the language of the question. It is not a filter, and a user should not be told
609
+ that one stopped the answer. It reads `answered`, `finish`, `finishReason` and `blockReason`, so it
610
+ works on `run.finish`'s result in the browser too.
558
611
 
559
- export function shownAnswer(result: AskResult): { text: string; note?: string } {
560
- if (!result.answered) {
561
- return { text: result.blockReason ? "This question was blocked by the model's safety filters." : "No answer this time. Ask again, or ask more precisely." };
562
- }
563
- if (result.finishReason === "model_context_window_exceeded") {
564
- return { text: result.text, note: "The answer was cut off: the chat filled the model's window." };
565
- }
566
- if (result.finishReason !== undefined && CUT_OFF.has(result.finishReason)) {
567
- return { text: result.text, note: "The answer was cut off at the model's output limit." };
568
- }
569
- return { text: result.text };
612
+ The messages of a chatbot for Hebrew speakers, with the English beside each:
613
+
614
+ | `reason` | Hebrew | English |
615
+ |---|---|---|
616
+ | `"filtered"` | התשובה נעצרה על ידי מסנן התוכן, ולכן היא לא מוצגת. | A content filter stopped the answer, so it is not shown. |
617
+ | `"cut"` | התשובה נקטעה כי הייתה ארוכה מדי. אפשר לבקש את ההמשך, או לשאול שאלה ממוקדת יותר. | The answer was cut off because it was too long. Ask for the rest, or ask a narrower question. |
618
+ | `"blocked"` | אי אפשר לענות על השאלה הזו. נסו לנסח אותה אחרת. | This question cannot be answered. Try putting it another way. |
619
+ | `"language"` | לא הצלחנו לענות בשפה של השאלה. נסו לנסח אותה שוב. | We could not answer in the language of the question. Try putting it again. |
620
+ | `"no_answer"` | לא התקבלה תשובה הפעם. נסו לשאול שוב, או לשאול בצורה מדויקת יותר. | No answer this time. Ask again, or ask more precisely. |
621
+ | `"other"` | משהו השתבש בזמן כתיבת התשובה. נסו שוב. | Something went wrong while the answer was written. Try again. |
622
+
623
+ ```ts
624
+ import { answerInfoOf, type AnswerInfo, type AskResult } from "llm-large-files";
625
+
626
+ const HEBREW: Record<NonNullable<AnswerInfo["reason"]>, string> = {
627
+ filtered: "התשובה נעצרה על ידי מסנן התוכן, ולכן היא לא מוצגת.",
628
+ cut: "התשובה נקטעה כי הייתה ארוכה מדי. אפשר לבקש את ההמשך, או לשאול שאלה ממוקדת יותר.",
629
+ blocked: "אי אפשר לענות על השאלה הזו. נסו לנסח אותה אחרת.",
630
+ language: "לא הצלחנו לענות בשפה של השאלה. נסו לנסח אותה שוב.",
631
+ no_answer: "לא התקבלה תשובה הפעם. נסו לשאול שוב, או לשאול בצורה מדויקת יותר.",
632
+ other: "משהו השתבש בזמן כתיבת התשובה. נסו שוב.",
633
+ };
634
+
635
+ /** The answer to show, and the note under it. Asked with filteredAnswer: "drop". */
636
+ export function shownAnswer(result: Pick<AskResult, "answered" | "text" | "finish" | "finishReason" | "blockReason">): { text: string; note?: string } {
637
+ const info = answerInfoOf(result);
638
+ if (info.complete) return { text: result.text };
639
+ // A reason of a later version reads as "other".
640
+ const message = HEBREW[info.reason ?? "other"] ?? HEBREW.other;
641
+ // A cut answer has text worth reading: the message goes under it.
642
+ return result.answered && result.text ? { text: result.text, note: message } : { text: message };
570
643
  }
571
644
  ```
572
645
 
646
+ The Gemini reasons behind each `finish`, and which of them a Vertex AI project can see (Model Armor
647
+ is Vertex only), are in [Vertex AI and Gemini](./vertex-and-gemini.md).
648
+
573
649
  ## Keeping what a failed question found
574
650
 
575
651
  `askWithFiles` throws the error as it came, and what the question did until then is not lost.
@@ -662,6 +738,42 @@ of another owner, is not an error of the store: `prepare` lists it in `missing`,
662
738
  throws `DocumentsNotFoundError` for it, unless `onMissingDocuments` says otherwise (below). What a
663
739
  store must do is in [Storage](./storage.md).
664
740
 
741
+ ### Transient errors: a store or a disk that does not answer
742
+
743
+ New in 0.10.0. A store that stops answering no longer holds a question forever. Every store call of
744
+ the library has a time limit, `storeTimeoutMs` (30 s by default): past it, the call is a
745
+ `DocumentStoreError` of code `"ETIMEDOUT"`, a 503 to retry. In a question it ends the question with
746
+ `run.error`, and the model sees no new text. While too many calls of the process are stuck past
747
+ their limit (`maxStuckStoreCalls`, half of `UV_THREADPOOL_SIZE`), store calls fail at once with code
748
+ `"STORE_STUCK"`, 503 too, so that the server keeps its threads for everything else. Both are
749
+ category `"store"` for `errorInfoOf`: the words of the `"store"` case above fit them ("try again in
750
+ a moment"). [Deployment](./deployment.md#a-store-that-stops-answering) says how to size the limits
751
+ and what to alert on.
752
+
753
+ A Node system error that says the server, or a service it needs, could not answer just now is now
754
+ retryable too: `ETIMEDOUT`, `ECONNRESET`, `ECONNREFUSED`, `EPIPE`, `EAI_AGAIN`, `EAGAIN`, `EBUSY`,
755
+ `EMFILE`, `ENFILE`, `ESTALE`, `EHOSTUNREACH` and `ENETUNREACH`. `errorInfoOf` gives them category
756
+ `"unknown"`, their code, status 503, `retryable: true` and 5 s to wait; a full disk (`ENOSPC`,
757
+ `EDQUOT`) the same with 30 s. The upload handlers answer them `503` with `Retry-After`. Before, they
758
+ were 500 and not retryable: a user was told "something went wrong" for a volume that hung a moment.
759
+ A path upload whose read does not answer within `ingestTimeoutMs` is such an error, `ETIMEDOUT`,
760
+ not the `IngestError` `"timeout"` (422, "split the file") it was: the trouble is the server's, not
761
+ the file's. The full list is in
762
+ [the reference](../reference/errors-and-retries.md#transient-system-errors).
763
+
764
+ Tell your users to try again when `retryable` is true, whatever the category:
765
+
766
+ ```ts
767
+ import { errorInfoOf } from "llm-large-files";
768
+
769
+ /** The Hebrew words for an error the user can retry: a store, a disk or a service that did not answer. */
770
+ export function retryWords(error: unknown): string | undefined {
771
+ const info = errorInfoOf(error);
772
+ if (!info.retryable || info.category === "model") return undefined; // a model's error has words of its own
773
+ return info.code === "ENOSPC" || info.code === "EDQUOT" ? "אין כרגע מקום בשרת. נסו שוב מאוחר יותר." : "השרת לא הגיב כרגע. נסו שוב בעוד רגע.";
774
+ }
775
+ ```
776
+
665
777
  ## Documents that are gone
666
778
 
667
779
  A document expires `ttlMs` after its upload (72 hours by default), and a chat can outlive it. By
@@ -694,7 +806,7 @@ the errors of another copy of the package too. Every row is in
694
806
  | `"model"` | A model request (`ModelRequestError`). | Its [kind](#the-kind-of-a-model-error). |
695
807
  | `"aborted"` | A signal stopped it: the user left, or a deadline. | `"aborted"`, `"timeout"`. |
696
808
  | `"input"` | A mistake in the call: a bug of your server, not of the user. | A scope error's code. |
697
- | `"unknown"` | Anything else. | A system error's code. |
809
+ | `"unknown"` | Anything else. Since 0.10.0 a system error that says the server could not answer just now (`ETIMEDOUT`, `ECONNRESET`…) is 503 and retryable ([transient errors](#transient-errors-a-store-or-a-disk-that-does-not-answer)). | A system error's code. |
698
810
 
699
811
  One switch turns them into your users' words. A chatbot for Hebrew speakers:
700
812
 
@@ -879,7 +991,7 @@ throws them: see [Testing](./testing.md).
879
991
  `ModelErrorKind`, `classifyModelError`, `errorKindOf`, `withRetry`, `RetryOptions`,
880
992
  `RetryNotice`, `isRetryableStatus`, `retryAfterMs`, the default waits.
881
993
  - [The tool loop](../reference/ask.md): `askWithFiles`, `AskResult`, `partialResultOf`,
882
- `DocumentsNotFoundError`.
994
+ `DocumentsNotFoundError`, `answerInfoOf` and `AnswerInfo`.
883
995
  - [The library](../reference/library.md): `DocumentStoreError`, `ingest`, `prepare`.
884
996
  - The adapters and their options: [Gemini](../reference/gemini.md),
885
997
  [OpenAI-compatible](../reference/openai.md), [Claude](../reference/anthropic.md).
@@ -92,7 +92,10 @@ What `askGemini` gives each model:
92
92
  `firstByteTimeoutMs`, `idleTimeoutMs` and `fetch` apply to both models. `analysisConfig` is the
93
93
  `generationConfig` of the part reads of a whole-file read, which the explorer makes: write it for
94
94
  the explorer. `toolFilePlacement: "inside"` is read by Gemini 3 models; if either model is
95
- Gemini 2.5, use `"beside"`, which both read (see [PDFs](./pdfs.md)).
95
+ Gemini 2.5, use `"beside"`, which both read (see [PDFs](./pdfs.md)). Since 0.10.0,
96
+ `timeoutMs` (the time of one part read), `analysisBody`, `functionCallingMode` and
97
+ `answerWithoutTools` apply to both models too. `body` goes to the chat requests of both, unless
98
+ `explorerBody` is set for the explorer.
96
99
  - **The defaults of `gemini()`.** `askGemini` has no option for `contextTokens`,
97
100
  `maxRequestBytes`, `pageTokens` or `id`, so both of its models keep the defaults of `gemini()`:
98
101
  no window and no request size declared, 530 tokens a page, and the model's name from its URL in
@@ -110,11 +110,16 @@ const openai = openAiCompatible({
110
110
  apiKey: process.env.OPENAI_API_KEY!,
111
111
  model: "gpt-5.5",
112
112
  contextTokens: 400_000,
113
- body: { reasoning_effort: "medium" }, // every chat request
114
- analysisBody: () => ({ reasoning_effort: "low" }), // the part reads of a whole-file read
113
+ body: { reasoning_effort: "none" }, // every chat request: tool calls need it (below)
114
+ analysisBody: () => ({ reasoning_effort: "low" }), // the part reads of a whole-file read, which offer no tools
115
115
  });
116
116
  ```
117
117
 
118
+ - **Tool calls on GPT-5.4 and later need `reasoning_effort: "none"`** through Chat Completions,
119
+ which is their default: with another effort and tools in the request, the API refuses the
120
+ request. The chat requests of the loop offer tools, so leave the effort out of `body`, or set
121
+ `"none"`. A part read offers no tools, and may reason. For reasoning with tools, OpenAI points to
122
+ its Responses API, which this adapter does not speak (planned for 1.0.0).
118
123
  - Part reads name their output limit `max_completion_tokens`, which OpenAI's newer models require.
119
124
  - A reasoning model sends nothing while it thinks. `firstByteTimeoutMs` (600 s) is the wait for
120
125
  its first piece. Its `completion_tokens_details.reasoning_tokens` are counted as
@@ -202,7 +207,33 @@ const deepseek = openAiCompatible({
202
207
  question and the request for an answer with no turn between them, and DeepSeek's reasoner
203
208
  refuses two user turns in a row.
204
209
  - **The model's own turn goes back with its `reasoning_content`**, streamed or not
205
- ([the reply](../reference/openai.md#openaicompatibleoptions)).
210
+ ([the reply](../reference/openai.md#openaicompatibleoptions)). Within a question the loop sends
211
+ it back.
212
+ - **Thinking mode and follow-up questions.** In a request with tools, DeepSeek's thinking mode
213
+ asks for the `reasoning_content` of every earlier assistant turn, those of earlier questions
214
+ included, even a turn that made no tool call, and refuses a request without it (HTTP 400). So
215
+ says its [thinking mode guide](https://api-docs.deepseek.com/guides/thinking_mode) (read in
216
+ November 2026). Without tools in the request, earlier reasoning is ignored. The library does not
217
+ keep the reasoning of an answer yet: `AskResult` does not give it, and a stored answer is a
218
+ `ChatTurn` of text. So a follow-up question that offers tools goes out without the reasoning of
219
+ the earlier answers, and DeepSeek refuses it. Thinking is on by default on DeepSeek's current
220
+ models. In a chat of several questions, turn it off for chat requests. The part reads of a
221
+ whole-file read offer no tools and do not use `body`, so they keep thinking:
222
+
223
+ ```ts
224
+ const deepseek = openAiCompatible({
225
+ baseUrl: "https://api.deepseek.com/v1",
226
+ apiKey: process.env.DEEPSEEK_API_KEY!,
227
+ model: "deepseek-v4-pro",
228
+ contextTokens: 128_000,
229
+ body: { thinking: { type: "disabled" } }, // chat requests: a follow-up offers tools
230
+ });
231
+ ```
232
+
233
+ A first question, with no earlier answer in `messages`, works with thinking on. The tool rounds
234
+ of earlier questions go back as their calls and results, without their reasoning, so they do
235
+ not give DeepSeek what it asks for either. Keeping the reasoning of earlier questions is planned
236
+ for a later version.
206
237
  - **`insufficient_system_resource`**: DeepSeek stops a reply when its servers run short. The
207
238
  adapter takes that for the server's failure, HTTP 503, and the loop sends the request again. A
208
239
  reply that is not streamed is checked before any of it is shown, so it can always be sent again;
@@ -380,9 +411,13 @@ the larger limit off when that allowance is no larger than 32,768. Both requests
380
411
  - **When a wait runs out**, the request is aborted with an `OpenAiRequestError` of status 0 and kind
381
412
  `"timeout"` ("The model sent nothing for 600 s."). `askWithFiles` sends it again once, unless
382
413
  text of it was already shown.
383
- - **A part read** has `timeoutMs` for the whole request, reply included. One that runs out is tried
384
- once more at once, and then counts as a part that could not be read, which the tool result says.
385
- Raise `timeoutMs` for a model that thinks long over a large part.
414
+ - **A part read** has `timeoutMs` for the whole request, reply included. One that runs out is an
415
+ `OpenAiRequestError` of status 0 and kind `"timeout"` ("The model took longer than 180 s to
416
+ answer."), since 0.10.0; before, the abort error of the timer, with no status, tried once more at
417
+ once. It is tried once more, after the retry wait (`retry.baseDelayMs`: 250 to 500 ms by default)
418
+ and with a `retry` event, and then counts as a part that could not be read, which the
419
+ tool result says ("The model took too long to answer."). Raise `timeoutMs` for a model that
420
+ thinks long over a large part; 0 sets none (since 0.10.0).
386
421
 
387
422
  How failed requests are sent again, and what to tell your user, is in
388
423
  [Errors and reliability](./errors-and-reliability.md).
@@ -590,7 +625,12 @@ Who does what, what changes for your application, and what it costs:
590
625
 
591
626
  Gemini also has an OpenAI layer, at `https://generativelanguage.googleapis.com/v1beta/openai`, and
592
627
  the adapter reads its errors, which come wrapped in a list. For Gemini, `gemini()` is the adapter to
593
- use: it sends pages to the model, which the layer refuses as a `file` part.
628
+ use: it sends pages to the model, which the layer refuses as a `file` part. The layer also leaves a
629
+ thinking model's thoughts out of its usage: in a live check in 0.10.0 on `gemini-3.8-flash`, its
630
+ `total_tokens` was about 46 more than `prompt_tokens` plus `completion_tokens`, with no
631
+ `reasoning_tokens`. Those tokens are billed, but `usage.outputTokens` does not hold them, and
632
+ `usage.thoughtTokens` is 0. `result.lastUsage` keeps the layer's own object, `total_tokens`
633
+ included.
594
634
 
595
635
  ## What was run live
596
636
 
@@ -720,8 +720,27 @@ refusing a whole-file read that would pass a ceiling of the question before it s
720
720
  bytes of the inline text.
721
721
  - `viewable`: the PDFs whose pages `view_pages` can show, because their uploaded file is kept
722
722
  (`keepOriginals`). Empty unless you pass `viewPages: true` and the store keeps originals.
723
- 2. **No tools needed?** When `plan.searchable` and `viewable` are both empty, every document is in
724
- the prompt: send one request without tools.
723
+ - New in 0.10.0: `toolable`, with `inlineTables: "tools"`. `instruction` and the blocks stay
724
+ those of 0.9 unless you ask for `numberInline` or `inlineTables`.
725
+
726
+ Two options of 0.10.0 change the text, and are off unless you ask for them:
727
+ - `numberInline: true` numbers the lines of each file sent whole as the tools number them
728
+ (`12| `), so that the model can cite its lines as it cites those of a searched file. The file is
729
+ planned by its numbered size, about 8% to 16% more tokens, so a file at the edge of
730
+ `inlineTokens` may become a card. `instruction` asks for citations only when a file is
731
+ searched. When none is (no tools, a table shown in full, a PDF whose pages can be looked at),
732
+ add `Cite line numbers like (report.docx L12).` to the system text after it.
733
+ - `inlineTables: "tools"` lists in `toolable` the files sent whole whose tables the tools can
734
+ count: a CSV or an XLSX workbook, or a DOCX, PPTX, PDF, HTML or Markdown file with a table of at
735
+ least 3 `| cell |` rows. Give them to `tools` with the searched files, so that a count over a
736
+ table shown in full is exact (`aggregate_table`), not done by eye. The block of each gives its
737
+ document_id in its first frame line, since the tools take it and it has no card.
738
+ `instruction` does not say that these tables can be counted. When `toolable` is not empty,
739
+ add after it the line `askWithFiles` adds: `Files shown in full can still be counted exactly:
740
+ use aggregate_table for counts, sums and groups over their tables, and search_document exact
741
+ for matching lines. In a spreadsheet, give the Row number when asked which row.`
742
+ 2. **No tools needed?** When `plan.searchable` and `viewable` are both empty, and `toolable` is
743
+ empty or not set, every document is in the prompt: send one request without tools.
725
744
  3. **Tools.** `files.tools(prepared.plan.searchable, options)` gives a `ToolSet`. The options that
726
745
  matter here: `access` (the owner and scope of step 1), `generate` (a `GenerateText`, which turns on `analyze_whole_document`; without it,
727
746
  plan with `wholeDocumentAnalysis: false` in step 1), `viewPages` (pass `prepared.viewable`, and
@@ -786,6 +805,7 @@ import {
786
805
  FINAL_ANSWER_REQUEST,
787
806
  jsonBytes,
788
807
  retryAfterMs,
808
+ TOOL_NAMES,
789
809
  toolResultSummary,
790
810
  UsageMeter,
791
811
  withRetry,
@@ -916,7 +936,9 @@ export async function ask(question: string, documentIds: string[], owner: string
916
936
  maxResultCharacters: Math.floor((tokensLeft * 2) / Math.min(calls.length, MAX_CALLS)),
917
937
  maxFileBytes: Math.floor(((budget.maxRequestBytes - sentBytes - 1_000_000) * 3) / 4), // base64: four bytes for three
918
938
  maxPages: pagesLeft,
919
- maxRequests: MAX_REQUESTS - usage.totals.requests - 1, // for a whole-file read; one is kept for the answer
939
+ // For a whole-file read, one is kept for the answer. A read_document call points at a whole
940
+ // read the model can make on its next turn at the earliest: that turn's request is kept too.
941
+ maxRequests: MAX_REQUESTS - usage.totals.requests - (call.name === TOOL_NAMES.read ? 2 : 1),
920
942
  });
921
943
  console.log(`${label}${toolResultSummary(label, output.result)}`);
922
944
  if (output.files.length > 0) {
@@ -965,9 +987,14 @@ into. Fill it from your own request, as the sample above does:
965
987
  - `maxFileBytes`: the room left in your request for the pages of this call, times 3/4 when files go
966
988
  as base64.
967
989
  - `maxPages`: the pages the question may still show. Lower it as the pages add up.
968
- - `maxRequests`: what your ceiling on requests has left, for a whole-file read. It only limits how
969
- many parts refused as too large are read again as two halves: a read that needs more parts than
970
- this still makes all of them, the merges of their notes and an answer.
990
+ - `maxRequests`: what your ceiling on requests has left, for a whole-file read. Since 0.10.0 a read
991
+ with more parts than this is refused before any request, and makes its merges within it; before,
992
+ it only limited how many parts refused as too large were read again as two halves. Give it to
993
+ `read_document` calls too, as the sample does (since 0.10.0): a read cut short of its range
994
+ points at a whole read of its file (`whole_file`) only when the file's parts are within it. The
995
+ model can call that read on its next turn at the earliest: `askWithFiles` keeps that turn's
996
+ request out of what it gives a `read_document` call, and gives 0 when it would not run a whole
997
+ read on that turn. Do the same in your loop.
971
998
  - `maxWaitMs` (new in 0.9.0): the most a look at pages waits for its turn, when that is less than
972
999
  the library's `pageLookWaitMs`. `askWithFiles` gives 0 to the looks of a turn after one was told
973
1000
  the server is busy (`onPagesBusy`, below), so that a wait that ends busy comes once in a turn. Do
@@ -72,8 +72,10 @@ pieces than 0.5.0 split it, which moves the lines after it. Since 0.8.0 the text
72
72
  (NFC): "e" and a combining accent become "é". Every format but log, JSON and CSV gets an outline
73
73
  from its headings: Markdown `#` lines (`## Slide N` and `## Sheet N: name` among them; not in a
74
74
  fenced code block, nor the comments of a text file that reads as code), chapter and numbered section
75
- lines, and short lines in capitals. `meta.pages` is the number of pages of a PDF, of slides of a
76
- PPTX and of sheets of an XLSX. [How it works](../how-it-works.md) follows ingest from there.
75
+ lines, and short lines in capitals; a PDF whose text gives fewer than 3 of these, from the lines set
76
+ in larger type than its body, when there are 3 or more ([PDF outline](#pdf-outline), new in
77
+ 0.10.0). `meta.pages` is the number of pages of a PDF, of slides of a PPTX and of sheets of an
78
+ XLSX. [How it works](../how-it-works.md) follows ingest from there.
77
79
 
78
80
  ### Text encodings
79
81
 
@@ -414,6 +416,7 @@ Figure 3: sales by region.
414
416
  - With `@cantoo/pdf-lib` installed, a page that shows a picture or a drawing gets the second line
415
417
  ([The line that marks a page](#the-line-that-marks-a-page)).
416
418
  - Tables are rebuilt as rows of cells ([PDF tables](#pdf-tables)).
419
+ - The lines set in larger type than the body are the outline ([PDF outline](#pdf-outline)).
417
420
 
418
421
  ### PDF tables
419
422
 
@@ -465,6 +468,87 @@ alone, `@cantoo/pdf-lib` still reads each PDF at ingest, for the page check, and
465
468
  process loads it, in one block of about 0.4 s. With `pictures: false` and `checkPages: false`,
466
469
  ingest does not use it at all ([Deployment](./deployment.md#uploads-and-ingest)).
467
470
 
471
+ ### PDF outline
472
+
473
+ The card and `get_document_overview` give the model an outline, headings with their line numbers,
474
+ and a search hit names the heading above it (`section`). The rules that find headings in a text
475
+ seldom find any in a PDF: pdf.js gives no blank line between paragraphs, and Hebrew has no capitals,
476
+ so an unnumbered Hebrew contract had no outline. Since 0.10.0 the PDF extractor finds the lines set
477
+ in larger type than the body, from the size pdf.js gives each piece of text, and `ingest` makes them
478
+ the outline of a PDF whose text gives fewer than 3 headings, when 3 or more of them are found in the
479
+ stored text. One or two are not an outline: a PDF with a title alone keeps the card and search hits
480
+ of 0.9.0. The card of a lease then starts its outline with:
481
+
482
+ ```text
483
+ Outline (8 of 8 headings):
484
+ L3 חוזה שכירות בלתי מוגנת
485
+ L6 הצדדים לחוזה
486
+ L9 פרטי השוכר
487
+ L16 תקופת השכירות
488
+ ```
489
+
490
+ - The body is the size most of the text is set in, table rows aside. A heading is a line at least
491
+ 15% larger, with three quarters of its characters in that size: the title, Word's Heading 1 and
492
+ Heading 2 (16 and 13 points over 11), the `h1` to `h3` of a page printed by Chrome.
493
+ - A table row is a line with a gap of more than 3 times its type size between two of its pieces:
494
+ cells, or a label and its value, whether the table was rebuilt or not (two columns, or
495
+ `tables: false`). It counts for neither the body nor the headings, so a statement whose table is
496
+ set smaller than its notes does not make its notes headings.
497
+ - Its level comes from its size. The sizes of several headings rank from the largest: 1, 2, then 3
498
+ for all smaller ones. A size of one heading only, larger than all of those (a title, the lines of
499
+ a cover page), is level 1, and the ranks then start at 2: a cover does not flatten the sections
500
+ and subsections under it.
501
+ - Each heading is a line of the stored text, and points to it: `read_document` from that line
502
+ starts at the heading. A heading set on several lines in a row is one entry, at its first line.
503
+ A line above it on its page that reads the same (a contents list, a running header in small type)
504
+ is passed over.
505
+ - Not headings: a line of more than 120 characters, or of fewer than 3 letters, or with more digits
506
+ than letters (a bare amount, a date in digits, a page number); a table row; a running header or
507
+ footer, which is a line found on 3 pages or more, or on 2 pages and at least half of them.
508
+ - A line that differs from those of other pages only by its numbers ("עמוד 3 מתוך 10", "Annual
509
+ Report page 7") is a page number, and not a heading, when it is found on at least half of the
510
+ pages, does not count up on one page (the same number in a page's header and its footer is one
511
+ page number), and does not count as section numbers do. Section numbers count
512
+ headings: each is the one before with one number 1 more, with pages without one between some of
513
+ them ("פרק 1" to "פרק 5" on the odd pages). A page number counts pages, and skips those it is
514
+ missing from: a header on the odd pages only reads "page 1", "page 3". Numbered headings several
515
+ to a page ("Article 1" to "Article 18", 3 to a page; "סעיף 1" to "סעיף 20", 2 to a page above
516
+ their titles) are always kept.
517
+ - No outline from sizes when more than 30% of the text is set larger than the body: the sizes then
518
+ mark something else.
519
+
520
+ It adds no line to the text: the text of a PDF, its reads and its pages are those of 0.9.0, and its
521
+ search hits the same but for the `section` they now name. What it does not find: a heading in bold
522
+ type of the body's size (pdf.js does not say which text is bold), a heading less than 15% larger
523
+ than the body (Word's Heading 3, 12 points over 11), a heading repeated on 3 pages or more,
524
+ numbered chapters one to a page on pages in a row that are at least half the document ("Chapter 1"
525
+ to "Chapter 4" on pages 1 to 4 of 6: they count as a page number does), and headings a PDF keeps
526
+ only in its bookmarks or tags. What it can take for a heading: any other short line set large, such
527
+ as a caption, a date written with its month's name, or a total with its label ("Total due
528
+ 12,500.00"); the header cell of a table that is not rebuilt when pdf.js gives it as a line of its
529
+ own; and a header row set large whose cells are closer than 3 times its type size, as in a narrow
530
+ table of two columns ("Field" and "Value"), which does not read as a table row. A PDF whose text
531
+ gives 3 headings or more (lines that start with `#`) keeps the outline of its text.
532
+
533
+ A PDF ingested before 0.10.0 keeps the outline it was given, most often none, until it is uploaded
534
+ again; the metadata does not say where an outline came from. The outline from sizes comes in
535
+ `ExtractedText.headings`: to keep the outline of the text alone, drop them in a wrapper.
536
+
537
+ ```ts
538
+ import { createLargeFiles, defaultExtractors, FileDocumentStore, type Extractor } from "llm-large-files";
539
+
540
+ // The outline of 0.9.0: from the text alone.
541
+ const pdfWithoutSizes: Extractor = async (bytes, input) => {
542
+ const { headings, ...extracted } = await defaultExtractors.pdf(bytes, input);
543
+ return extracted;
544
+ };
545
+
546
+ export const files = createLargeFiles({
547
+ store: new FileDocumentStore("./data/large-files"),
548
+ extractors: { pdf: pdfWithoutSizes },
549
+ });
550
+ ```
551
+
468
552
  ## Pictures in PDFs
469
553
 
470
554
  The text of a PDF does not hold its photos, charts and diagrams. Asked about a bar chart from the
@@ -962,6 +1046,10 @@ What the library does with what you return:
962
1046
  your extractor stored as U+FFFD. Both reach the card, the frame of a file sent whole, and
963
1047
  `toDocumentSummary` ([Text encodings](#text-encodings)).
964
1048
  - A `text` file whose lines look like a log becomes `log`.
1049
+ - `headings`, for a PDF, become its outline when its text gives fewer than 3 headings and 3 or more
1050
+ of them are found ([PDF outline](#pdf-outline)): each is looked for among the lines of its page,
1051
+ after the line `--- Page N ---`, by its text without spaces, past the `skip` lines of its page
1052
+ that read the same. New in 0.10.0.
965
1053
 
966
1054
  An error you throw is the answer to the upload. `ingest` throws it as an `IngestError` with the
967
1055
  same message (and your error as `cause`), with the code its message gives
@@ -1057,7 +1145,8 @@ const pdfWithOcr: Extractor = async (bytes, input) => {
1057
1145
  // Nothing recognized in a PDF without any text: the built-in rules decide. It is refused, or
1058
1146
  // accepted when its pages can be shown.
1059
1147
  if (filled === 0 && blank === extracted.pages) return builtIn(bytes, input);
1060
- return { text, pages: extracted.pages };
1148
+ // The rest as the built-in extractor returned it: `pages`, and the headings of the outline.
1149
+ return { ...extracted, text };
1061
1150
  };
1062
1151
 
1063
1152
  export const files = createLargeFiles({
@@ -1068,10 +1157,10 @@ export const files = createLargeFiles({
1068
1157
  ```
1069
1158
 
1070
1159
  What this keeps: the page lines, so search results still give page numbers; `pages`; the rebuilt
1071
- tables and the picture marks of the pages that had text; and the picture line over a scanned page,
1072
- since the model can still look at it to check a stamp or a signature. Only PDFs with a page without
1073
- text go to the OCR service, and only those pages change. A scan of any length is accepted once OCR
1074
- found text in it.
1160
+ tables, the picture marks and the outline from type sizes of the pages that had text; and the
1161
+ picture line over a scanned page, since the model can still look at it to check a stamp or a
1162
+ signature. Only PDFs with a page without text go to the OCR service, and only those pages change. A
1163
+ scan of any length is accepted once OCR found text in it.
1075
1164
 
1076
1165
  OCR runs inside `files.ingest`, so the upload waits for it, and it counts toward `ingestTimeoutMs`
1077
1166
  (2 minutes by default). For long scans, raise `ingestTimeoutMs` (0 sets no limit), run ingest in a