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
@@ -52,8 +52,9 @@ export async function ask(userId: string, documentIds: string[], question: strin
52
52
  toolTurns: 8, // at most 8 chat requests, the answer included, plus one when the answer comes back without text
53
53
  callsPerTurn: 6, // at most 6 tool calls run in one turn
54
54
  wholeDocumentReads: 1, // each document is read whole once at most (the default)
55
- inputTokens: 1_500_000, // no more tools once the question has used this many input tokens
55
+ inputTokens: 1_500_000, // no more tools once the next request and the answer would pass this many input tokens
56
56
  requests: 30, // chat requests and part reads together
57
+ wholeReadsPerQuestion: 2, // at most 2 whole-file reads in all (the default)
57
58
  },
58
59
  });
59
60
  console.log(result.turns, result.usage);
@@ -66,7 +67,8 @@ export async function ask(userId: string, documentIds: string[], question: strin
66
67
  | `toolTurns` | 12 | Chat requests of the question: the answer and the second tries after an empty or broken turn included. The second try of the answer itself, when it came back without text, can be one request past it. | The last request must be answered in text (`toolChoice: "none"`; Gemini gets no tools declared, the other adapters keep them listed). |
67
68
  | `callsPerTurn` | 8 | Tool calls of one model turn that are run. | Each call past it is answered "Not run: one turn runs at most 8 tool calls. Send this call again if you still need it." |
68
69
  | `wholeDocumentReads` | 1 | Whole-file reads of each document. | A read past it is answered with an error that tells the model to use the answer it already has. 0 refuses every read. |
69
- | `inputTokens` | none | Input tokens of the question: every chat request and part read, of every model. | No more tools run: the next request is the answer. A whole-file read that would pass it is refused before it starts. |
70
+ | `wholeReadsPerQuestion` | 2 | Whole-file reads of the question, over all its documents. New in 0.10.0. | A read past it is refused: "Not run: one question makes at most 2 whole-file reads, and this one has made them. Use search_document and read_document on app.log." |
71
+ | `inputTokens` | [the default ceiling](#the-default-ceiling) | Input tokens of the question: every chat request and part read, of every model, by the provider's count, or by the library's estimate when a request reports none. | When the next tool request and the answer would pass it, no more tools run: the next request is the answer. A whole-file read that would pass it is refused before it starts. |
70
72
  | `requests` | none | Answered requests of the question: chat requests and part reads together. | Once one request is left, no more tools run, and that request is the answer. A whole-file read that would pass it is refused before it starts. |
71
73
 
72
74
  **No limit throws.** A question that reaches a limit ends with a request for the answer, written
@@ -81,38 +83,78 @@ true when the reply has text and was not refused.
81
83
  the model was told not to make. The note "Your last reply had no text. No tool can be called in
82
84
  this reply: write the answer now, in text, from what is above." goes at the end of that one
83
85
  request. It is one of the two second tries a question may make, and it can be one request past
84
- `toolTurns`. It is not made after a refusal, a filter or a reply cut off at the output limit with
85
- nothing in it, nor once `requests` or `inputTokens` is reached: those two are never passed by
86
- it. With `toolTurns: 8`, a question makes at most 9 answered chat requests; to cap them exactly,
87
- set `requests`.
86
+ `toolTurns`. It is not made after a refusal, a filter, another reason that asking again does
87
+ not mend (`finish: "other"`, such as Gemini's `OTHER` or `LANGUAGE`) or a reply cut off at the
88
+ output limit with nothing in it, nor when it would pass `requests` or the ceiling of input
89
+ tokens: it is sent only while a request is left of `requests`, and while what the question spent
90
+ and that request, as the loop estimates it, stay within the ceiling. With `toolTurns: 8`, a
91
+ question makes at most 9 answered chat requests; to cap them exactly, set `requests`.
88
92
  - Each tool result carries `tool_turns_left`, so the model can see its turns run out and stop
89
93
  searching in time. The results of an earlier question, passed back in `messages`, are sent
90
94
  without it ([Conversations](./conversations.md#what-toolturns-holds)).
91
95
  - A model that answers in text before a limit is reached ends the question there.
92
- - The result does not say that a limit ended the question, and `steps` has no line for it. When
93
- `result.turns` reaches `toolTurns`, the model was most likely still calling tools when its turns
94
- ran out. `result.usage` shows how close the question came to `inputTokens` and `requests`.
96
+ - The result does not say that a limit ended the question, and `steps` has no line for it. A
97
+ `budget_reached` notice says it once when `inputTokens` or `requests` stopped the tools
98
+ ([events](../reference/events.md#noticecode-and-noticedisplay)). When `result.turns` reaches
99
+ `toolTurns`, the model was most likely still calling tools when its turns ran out.
100
+ `result.usage` shows how close the question came to `inputTokens` and `requests`.
95
101
  - With an explorer model, the limits count the work of both models together. The answer is always
96
102
  a request of its own, so the explorer has at most `toolTurns − 1` requests
97
103
  ([explorer model](./explorer-model.md)).
98
104
  - `maxToolTurns` and `maxToolCallsPerTurn` of `askGemini` are `toolTurns` and `callsPerTurn` under
99
105
  their names from before 0.5.0. When both are given, `limits` wins.
100
106
 
101
- ### `inputTokens` and `requests` are checked between turns
102
-
103
- - **They are checked before each tool turn**, against what the question has used so far. The
104
- request that crosses `inputTokens` has already been sent: its tool calls run, and then the answer
105
- is asked for. So a question can pass `inputTokens` by about two requests: the one that crossed
106
- it, and the answer, which reads everything the tools returned. Set the ceiling that far below
107
- what must not be passed.
107
+ ### The default ceiling
108
+
109
+ New in 0.10.0: a question that sets no `inputTokens` still has a ceiling. One runaway question, a
110
+ model that reads eight more pieces of a log in every turn and never answers on its own, made 13
111
+ requests and about 6.9 million input tokens with no ceiling. A default bounds what one question can
112
+ cost when nobody set a ceiling. It is the larger of these two, with room for whole-file reads added:
113
+
114
+ - [`DEFAULT_INPUT_TOKENS`](../reference/ask.md#default_input_tokens): 1,000,000;
115
+ - `toolTurns` times the estimate of the question's first request. A long conversation makes the
116
+ first request large, and every tool request carries it again: the ceiling grows with it.
117
+
118
+ **The room for whole-file reads** is as many reads as the question may make (`wholeReadsPerQuestion`,
119
+ and `wholeDocumentReads` of each document that can be read whole), each at the price of the dearest
120
+ of those documents (see [below](#the-ceiling-looks-ahead)). It is 0 when no document of the question
121
+ can be read whole, or `analyze_whole_document` is not offered. So a read of a 1.77 MB log in parts of
122
+ 60,000 tokens, about 1.5 million input tokens, runs under the default; a third read in one question
123
+ does not (`wholeReadsPerQuestion`).
124
+
125
+ Typical questions are far below it: four tool turns over a 3 MB log use less than half of
126
+ 1,000,000, and make the same requests as with no ceiling. `limits: { inputTokens: Infinity }` gives
127
+ the behavior of 0.9: no ceiling.
128
+
129
+ ### The ceiling looks ahead
130
+
131
+ - **It is checked before each tool request**, looking ahead: what the question has spent, the tool
132
+ request about to be sent and the request for the answer after it, as the loop estimates them now
133
+ (raised by what the provider reported for the requests before). When the three would pass the
134
+ ceiling, no tool request is made, and the next request is the answer. So a question spends at most
135
+ about one request past its ceiling: the answer's, with the results of the last tool turn in it.
136
+ The answer's second try, after a reply without text, looks ahead the same way: it is not made when
137
+ it would pass the ceiling. In 0.9 the ceiling was checked after the fact: a ceiling of 500,000 let
138
+ 1,219,683 tokens through.
139
+ - **A request that reports no input is counted by its estimate.** An OpenAI-compatible server that
140
+ sends no usage, a provider that reports an input of 0, or a part reader of your own that does not
141
+ call `onUsage`: the loop adds its estimate of that request to `usage.estimatedInputTokens`, and
142
+ counts it in `usage.unmeasuredRequests`. The ceiling counts both: `usage.inputTokens +
143
+ usage.estimatedInputTokens`. In 0.9 such a question never reached its ceiling.
108
144
  - **`requests` keeps one request for the answer**, so the answer stays within it.
109
- - **A whole-file read is reckoned before it starts.** In input tokens, it is the size of the file
110
- in the tokens of the model that reads it. In requests, it is its parts, one merge of their notes,
111
- its answer, and the answer of the question. A read that does not fit what is left is not run, and
112
- costs nothing. The model gets the reason, for example: "Not run: reading all of app.log takes
113
- about 2,400,000 input tokens, and 900,000 are left of the 1,500,000 this question may use. Use
114
- search_document and read_document." Reads let through in the same turn share what is left. A read
115
- whose notes need more than one merge can pass `requests` by those merges.
145
+ - **A whole-file read is priced before it starts.** In input tokens, by what its requests send: the
146
+ file's lines with their numbers, the prompt of each part, the merges of their notes and the read's
147
+ own answer, in the tokens of the model that reads it. That is about 10% more than the file itself
148
+ for a log, and more again when its notes need merges. In requests, it is its parts, one merge of
149
+ their notes, its answer, and the answer of the question. A read that does not fit what is left is
150
+ not run, and costs nothing. The model gets the reason, for example: "Not run: reading all of
151
+ app.log takes about 2,400,000 input tokens, and 900,000 are left of the 1,500,000 this question may
152
+ use. Use search_document and read_document." Reads let through in the same turn share what is
153
+ left. A read whose notes need more than one merge can pass `requests` by those merges.
154
+ - **A read that failed is not priced again.** When a whole-file read of a document sent its parts
155
+ and could read none of them, a second call for it is answered by the tool with that reason ("The
156
+ whole-file read of app.log failed earlier in this question (…), and is not tried again."), not
157
+ with its price.
116
158
  - **A request that failed and was sent again counts once**, as it does in `usage`.
117
159
 
118
160
  ### Tools you can leave out
@@ -375,7 +417,10 @@ What each provider's numbers become:
375
417
  have billed it: a stream cut off half-way, or a wait on a silent model that ran out. Your
376
418
  provider's bill is the record; `usage` is a close account of it.
377
419
  - **A request without usage counts with 0 tokens**: an OpenAI-compatible server that sends no
378
- usage, or a part reader of your own that does not call `onUsage`.
420
+ usage, or a part reader of your own that does not call `onUsage`. Since 0.10.0 its input is
421
+ counted apart, by the library's estimate: `estimatedInputTokens`, in each model's own tokens,
422
+ and `unmeasuredRequests`. Both are absent when every request reported its input. The ceiling of
423
+ the question counts them; your cost accounting may too, as an estimate.
379
424
  - **`byModel` is keyed by the adapter's `id`.** For `gemini()` that is the model named in the URL
380
425
  (`"gemini-3.8-flash"`); for `openAiCompatible()` and `anthropic()`, the `model` option; for any of
381
426
  them, the `id` option when you set it. A part read counts under the model that read it: the
@@ -509,7 +554,8 @@ export async function answer(sessions: Sessions, userId: string, sessionId: stri
509
554
  ### An allowance per user
510
555
 
511
556
  To keep a user within an allowance, turn what the user has left into `limits.inputTokens` of the
512
- next question. Keep a margin: a question can pass its ceiling by about two requests.
557
+ next question. Keep a margin: a question can pass its ceiling by about one request, the answer's
558
+ ([The ceiling looks ahead](#the-ceiling-looks-ahead)).
513
559
 
514
560
  ```ts
515
561
  import { askGemini } from "llm-large-files/gemini";
@@ -517,7 +563,7 @@ import { askGemini } from "llm-large-files/gemini";
517
563
  // files and endpoint as in the first sample. spentThisMonth: the user's input tokens this month,
518
564
  // from your records. userId, documentIds and messages are yours.
519
565
  const allowance = 50_000_000; // input tokens a month: your own figure
520
- const margin = 2_000_000; // about two requests of a 1M-token window
566
+ const margin = 1_000_000; // about one request of a 1M-token window
521
567
  const left = allowance - spentThisMonth;
522
568
  if (left <= margin) throw new Error("You have used this month's allowance.");
523
569
 
@@ -588,8 +634,10 @@ totals do not have. More on wrapping an adapter: [your own adapter and loop](./o
588
634
 
589
635
  What bounds it:
590
636
 
591
- - `limits.wholeDocumentReads` (1 per document by default), `wholeDocumentAnalysis: false`, and
592
- `limits.inputTokens` and `limits.requests`, which refuse a read that would pass them.
637
+ - `limits.wholeDocumentReads` (1 per document by default), `limits.wholeReadsPerQuestion` (2 in
638
+ all by default, new in 0.10.0), `wholeDocumentAnalysis: false`, and `limits.inputTokens` and
639
+ `limits.requests`, which refuse a read that would pass them. The default ceiling leaves room for
640
+ the reads the question may make ([the default ceiling](#the-default-ceiling)).
593
641
  - With your own loop, the same cap is `maxWholeDocumentReads` of `files.tools()`
594
642
  (`MAX_WHOLE_DOCUMENT_READS`, 1, by default), counted per tool set: make one for each question
595
643
  ([your own adapter and loop](./own-adapter-and-loop.md)).
@@ -607,12 +655,15 @@ What bounds it:
607
655
  Each chat request sends everything before it. One tool result may be up to `toolResultCharacters`
608
656
  (24,000 characters, about 12,000 tokens of a log), up to 8 run in a turn, and every result stays in
609
657
  the requests until the answer. Text tool results may fill the window up to
610
- `contextTokens − reservedTokens / 2`: 968,000 tokens with the default budget. So the bound with the
611
- defaults is 12 requests of up to about 968,000 tokens each, about 11.6 million input tokens, plus a
612
- whole-file read of each document searched. A question of a few searches and reads is far from that
613
- bound: [measurements](../measurements.md) has live numbers.
614
-
615
- What bounds it: `limits.toolTurns` and `limits.callsPerTurn`; `limits.inputTokens`;
658
+ `contextTokens − reservedTokens / 2`: 968,000 tokens with the default budget. So with no ceiling
659
+ the bound is 12 requests of up to about 968,000 tokens each, about 11.6 million input tokens, plus a
660
+ whole-file read of each document searched. Since 0.10.0 the default ceiling stops the tools near
661
+ 1,000,000 input tokens (one request past it at most, and room for the whole-file reads the question
662
+ may make). A question of a few searches and reads is far from either: [measurements](../measurements.md)
663
+ has live numbers.
664
+
665
+ What bounds it: `limits.toolTurns` and `limits.callsPerTurn`; `limits.inputTokens`, by default
666
+ since 0.10.0;
616
667
  `budget.toolResultCharacters` (smaller results, though the model may then need more reads); and an
617
668
  explorer model, which makes these requests at its own price.
618
669
 
@@ -646,6 +697,46 @@ repeats cheaper ([below](#prompt-caching)).
646
697
  sent whole can take several when the document is searched.
647
698
  - Name in `documentIds` only the documents a question is about. Each one named is planned: sent
648
699
  whole, or given a card.
700
+ - Since 0.10.0 their lines are numbered (`numberInline`), so that the answer can cite them: about
701
+ 8% to 16% more tokens for each file sent whole (15.5% for a CSV of short rows, 9.4% for a service
702
+ log, 8.4% for Hebrew prose). A file at the edge of `inlineTokens` may become a card for it.
703
+ `numberInline: false` sends them as 0.9 did.
704
+
705
+ ### Tables sent whole
706
+
707
+ Since 0.10.0 a table sent whole (a CSV, an XLSX workbook, a file with `| cell |` rows) gets
708
+ `search_document`, `read_document` and `aggregate_table` (`inlineTables: "tools"`, the default), so
709
+ that counts and sums over it are exact, not made by eye. What a question costs then:
710
+
711
+ - **A question that needs no count** stays at one request when the model answers at once, as it
712
+ does when the answer is in the table it sees. The request is a little larger, by the three tool
713
+ declarations and one line of the system text (about 1,500 tokens). Some models look the row up
714
+ with a tool anyway, which takes 2 requests: in the live checks of 0.10.0, Flash-Lite did so for
715
+ about half of these questions, and Flash rarely
716
+ ([measurements](../measurements.md#tables-sent-whole-p1s-live-gate)). A reply that ends with no
717
+ text and no call, and not by a filter or the output limit, is asked again once with a note, as in
718
+ any question: one request more, with the table.
719
+ - **A count** takes about 3 requests: one that calls `aggregate_table` (or an exact search), one
720
+ that answers from its result, and sometimes one more call. Each sends the table again. For a CSV
721
+ of 3,000 invoices (113,000 estimated tokens, 131,000 with its lines numbered), one request of 0.9
722
+ becomes about three of 131,000 tokens each: about 400,000 input tokens by the library's estimate.
723
+ Requests two and three start as the first did, so a provider whose cache matches that start
724
+ (Gemini's implicit cache on Vertex AI) bills most of them at the cached price.
725
+ - **With an explorer**, a question in which no file is searched and a table sent whole gets the
726
+ tools is run by the answering model alone: the explorer would send every file sent whole again,
727
+ to a model that does not share the other's cache.
728
+ - **At most**, a model that goes on calling tools uses the question's ceiling: by default about
729
+ `toolTurns` times its first request (`DEFAULT_INPUT_TOKENS`, 1,000,000, at least). For the CSV of
730
+ 3,000 invoices that is 11 requests of about 134,000 tokens, about 1.5M input tokens, where
731
+ `"text"` makes one request of 133,000. `limits.inputTokens` or `limits.toolTurns` bound it.
732
+ - **Limits sized for 0.9.** A count needs room for about three requests with the table. A ceiling
733
+ (`limits.inputTokens`) or `limits.requests` sized for 0.9's one request leaves no tool turn, and
734
+ so does `limits.toolTurns: 1`: such a question is then the one request of `"text"`, without the
735
+ tools, and its counts are made by eye again.
736
+
737
+ To keep the cost of 0.9 for such questions, at the price of counts made by eye, pass
738
+ `inlineTables: "text"`. A lower `inlineTokens` sends the table as a card instead: its requests are
739
+ small, and the model reads it only through the tools.
649
740
 
650
741
  ### An explorer model
651
742
 
@@ -685,6 +776,9 @@ What the library changes:
685
776
 
686
777
  - A document that went whole can become a card as the history grows (above). The tool guide, which
687
778
  names the files that are searched, changes with it.
779
+ - The tools declared follow the files of the question. Since 0.10.0 a table sent whole gets three
780
+ of them and a line of the system text ([Tables sent whole](#tables-sent-whole)), so a table
781
+ added to a chat whose files were all sent whole adds tools to its requests.
688
782
  - Within a question, when room runs short, older tool results are replaced by short stand-ins. The
689
783
  request changes from the first round replaced. A model whose conversation may only grow (Claude)
690
784
  has nothing of the question replaced. Since 0.9.0 the stored rounds of earlier questions are
@@ -702,7 +796,7 @@ What the library changes:
702
796
  questions were already sent that way, and still match. The documents and cards before them are
703
797
  still read from the cache. Pages up to 0.8.2 named `tool_turns_left` alone; with a model that
704
798
  thinks, the signatures make the miss on their own. Keeping the model's own turns is planned for
705
- 0.10.0.
799
+ a later version.
706
800
  - An upgrade that changes the library's prompts misses the cache once in each conversation. 0.6.0
707
801
  changed the tool guide, the descriptions of `search_document` and `analyze_whole_document`, and
708
802
  the frame lines of a file sent whole. The first request after the upgrade shares with what 0.5.0
@@ -712,7 +806,9 @@ What the library changes:
712
806
  instruction. For a question whose files are all sent whole, it is your own system text, and
713
807
  `view_pages` with its guide when the pages of a PDF can be looked at. From then on the frame of a
714
808
  document is the same in every request
715
- ([Deployment](./deployment.md#servers-of-two-versions)).
809
+ ([Deployment](./deployment.md#servers-of-two-versions)). 0.10.0 changes the text again: files
810
+ sent whole are numbered, a table sent whole gets tools, and `analyze_whole_document` is declared
811
+ with two more arguments ([Upgrading to 0.10](../upgrading-0.10.md)).
716
812
 
717
813
  The adapters:
718
814
 
@@ -2,9 +2,9 @@
2
2
 
3
3
  This page is for running an application built on llm-large-files in production: on several
4
4
  servers, behind a proxy or a load balancer, through restarts and upgrades. It says what state lives
5
- where, what the shared store must guarantee, how much memory a server needs, how to sweep expired
6
- documents, how to keep a streamed answer alive, and what Node.js and packages a production image
7
- needs.
5
+ where, what the shared store must guarantee, what happens when it stops answering, how much memory
6
+ a server needs, how to sweep expired documents, how to keep a streamed answer alive, and what
7
+ Node.js and packages a production image needs.
8
8
 
9
9
  ## What lives where
10
10
 
@@ -22,6 +22,7 @@ rebuild from the store.
22
22
  | Searches of large files waiting their turn | A queue in each `LargeFiles` (`maxConcurrentScans`) | No | Empty |
23
23
  | Ingests waiting their turn | A queue in each `LargeFiles` (`maxConcurrentIngests`, new in 0.8.2) | No | Empty: the uploads in it get no answer, and must be sent again |
24
24
  | Uploads being received | A count in each set of `createDocumentHandlers` (`maxPendingUploadBytes`, new in 0.8.2) | No | Empty |
25
+ | Store calls past their time limit that have not ended | A count in each process (`files.stats().stuckStoreCalls`, new in 0.10.0) | No | Zero |
25
26
  | The output limit a thinking model needs for whole-file part reads | Each process, by URL and model | No | Learned again, at the cost of one request |
26
27
  | The name of the output limit an OpenAI-compatible server takes | Each `openAiCompatible()` adapter | No | Learned again, at the cost of one refused request |
27
28
 
@@ -102,6 +103,84 @@ The built-in stores:
102
103
  - **A store of your own**, over MongoDB, S3, Cloud Storage, Redis or a database: see
103
104
  [Storage](./storage.md) for the contract method by method and a complete example.
104
105
 
106
+ ## A store that stops answering
107
+
108
+ A network volume can stop answering without failing: an NFS server that is gone, a mount that
109
+ hangs. Before 0.10.0 a question whose store call did not answer waited forever, and so did
110
+ `files.delete`. Since 0.10.0 every store call of the library has a time limit, `storeTimeoutMs`,
111
+ 30 seconds by default: a look-up (`getMeta`), a read of a text whole or by range, of its index or
112
+ of its original, and a delete. Past it, the call fails with a `DocumentStoreError` of code
113
+ `"ETIMEDOUT"`, a 503 that `errorInfoOf` marks as one to retry. In a question it ends the question
114
+ with `run.error`; the upload handlers' `remove` answers 503 with `Retry-After`. `ingest` keeps its
115
+ own limits (`ingestTimeoutMs`), and `sweep` has `sweepTimeoutMs`
116
+ ([below](#sweeping-expired-documents)).
117
+
118
+ **Size it** above the slowest healthy call: a read of the largest text loaded whole
119
+ (`wholeDocumentBytes`, 2 MB by default) or of the largest original a look at pages reads, over your
120
+ volume at its busiest. Raise it for a slow store, or set 0 for no limit.
121
+
122
+ **The thread pool.** A call to the disk that does not answer cannot be stopped: Node.js gives up
123
+ waiting for it, and the call holds one thread of libuv's pool until the volume answers. The pool
124
+ has 4 threads by default, and every file call of the process uses it, and so does every DNS look-up
125
+ (`dns.lookup`, which `fetch` calls for each new connection, to Vertex AI too). Measured on Node 22
126
+ with calls that never end (opens of a FIFO with no writer, as a hung NFS mount behaves):
127
+
128
+ | Threads (`UV_THREADPOOL_SIZE`) | Calls stuck | A read of another file | `dns.lookup("localhost")` |
129
+ |---|---|---|---|
130
+ | 4 (the default) | 3 | 9 ms | 13 ms |
131
+ | 4 (the default) | 4 | still waiting after 2 s | still waiting after 2 s |
132
+ | 32 | 4 | 2 ms | 13 ms |
133
+
134
+ So on servers that use a network volume, set `UV_THREADPOOL_SIZE=32` in the environment of the
135
+ process (the pool is made at the first call that needs it: setting it in your code later may do
136
+ nothing). Check that the value reaches the process: libuv reads an empty value, 0, or one that
137
+ does not start with digits as a pool of 1 thread, where one stuck call freezes every file call. A
138
+ template whose value is unset can give an empty one.
139
+
140
+ **Calls left stuck.** A call counts as stuck once it has run past `storeTimeoutMs`, whether its
141
+ caller timed out or left, until it ends. One that ends within the limit never counts, so users who
142
+ press stop during slow but healthy reads do not raise it. The count is the process's, as the pool
143
+ is: the calls of every library, the writes and look-ups of `ingest` past `ingestTimeoutMs` (the
144
+ time it gives them, so that a large upload written slowly is not counted at 30 s), and the upload
145
+ handlers' calls to the disk past `uploadIdleTimeoutMs`. While it is at `maxStuckStoreCalls`, every
146
+ new store call of the library, those of `ingest` included, fails at once with code `"STORE_STUCK"`
147
+ (503), without touching the volume, so that the threads left keep serving file calls and DNS. The
148
+ default is half the pool, read from `UV_THREADPOOL_SIZE` when the library is made: 2 with 4
149
+ threads, 16 with 32. Deletes of one library run one at a time, so a volume that hangs holds one
150
+ thread for them, not one for each.
151
+
152
+ **Alerts and readiness.** `files.stats()` and `handlers.stats()` read counters only, with no store
153
+ call: call them as often as your metrics need.
154
+
155
+ ```ts
156
+ import http from "node:http";
157
+
158
+ // One library and one set of handlers per process, made at startup.
159
+ let stuckSince: number | undefined;
160
+ http.createServer((request, response) => {
161
+ const stats = files.stats();
162
+ const uploads = handlers.stats();
163
+ if (request.url === "/metrics") {
164
+ response.setHeader("Content-Type", "application/json");
165
+ return void response.end(JSON.stringify({ ...stats, uploads }));
166
+ }
167
+ // Ready unless this pod is saturated, or its calls have been stuck at the limit for a minute.
168
+ const atLimit = stats.stuckStoreCalls >= stats.maxStuckStoreCalls;
169
+ stuckSince = atLimit ? (stuckSince ?? Date.now()) : undefined;
170
+ const ready = stats.ingests.waiting <= 20 && !(stuckSince !== undefined && Date.now() - stuckSince >= 60_000);
171
+ response.statusCode = ready ? 200 : 503;
172
+ response.end(ready ? "ready" : "busy");
173
+ }).listen(9090);
174
+ ```
175
+
176
+ - **Alert on `stuckStoreCalls` above 0.** It means the store stopped answering on that pod.
177
+ - **Fail readiness on local saturation**: `ingests.waiting`, `pageLooks.waiting` or
178
+ `uploads.uploadsInFlight` past a bound you choose. Another pod can take the next request.
179
+ - **Fail readiness on stuck calls only when they stay at the limit for 60 s or more.** All pods
180
+ share one volume: when it hangs, a readiness probe that fails at once takes every pod out at
181
+ once, and users get the ingress's error instead of your app's "try again". A short hang then
182
+ costs a few 503s, which your app tells as a store to retry.
183
+
105
184
  ## Memory on each server
106
185
 
107
186
  | What takes memory | How much | What bounds it |
@@ -266,15 +345,18 @@ const documents = createDocumentHandlers(files, {
266
345
  On a network volume, that is the price of taking it off the heap.
267
346
  - **A volume that stops answering.** Each call to the disk (opening the file, each write, closing
268
347
  it) is waited for no longer than `uploadIdleTimeoutMs` (30 s). Past it, the upload is answered
269
- `500` `{ "error": "Upload failed (ETIMEDOUT)." }`, and its room is given back. The file is removed
348
+ `503` `{ "error": "Upload failed (ETIMEDOUT)." }` with `Retry-After: 5` (a `500` before 0.10.0),
349
+ its room is given back, and the call counts as stuck until it ends
350
+ ([A store that stops answering](#a-store-that-stops-answering)). The file is removed
270
351
  at once, or once the volume answers. On a network volume, closing a file can wait for the writes
271
352
  the system held back: on a slow one, raise `uploadIdleTimeoutMs`. The same holds for the `path`
272
353
  of `prepareUpload`, and for the check of its folders with a ref. The removal of the file, once
273
354
  the ingest ends, is waited for no longer either: the upload is answered, its room is given back,
274
355
  and the removal goes on alone. The ingest's look at the file before its turn, and its read at its
275
- turn, are waited for no longer than `ingestTimeoutMs` (2 minutes by default). Past it, the look
276
- is answered `500` `{ "error": "Upload failed (ETIMEDOUT)." }`. The read fails as a file that took
277
- too long to read: `422`, code `"timeout"`. Until then, the upload holds its room. With
356
+ turn, are waited for no longer than `ingestTimeoutMs` (2 minutes by default). Past it, both are
357
+ answered `503` `{ "error": "Upload failed (ETIMEDOUT)." }` with `Retry-After: 5`. Before 0.10.0
358
+ the look was a `500`, and the read failed as a file that took too long to read (`422`, code
359
+ `"timeout"`, "split it"), though the trouble was the volume's. Until then, the upload holds its room. With
278
360
  `ingestTimeoutMs: 0`, the look still stops at 2 minutes, but the read waits until the client
279
361
  leaves.
280
362
  - **Saving the upload where you keep it.** When your app keeps each upload anyway, `prepareUpload`
@@ -598,8 +680,9 @@ and then the model is told the server is busy. So the heap holds one parsed PDF
598
680
  for each question that looks. Raise it only with the heap to match: six looks at once took 352 MB
599
681
  more than one, and did not finish sooner. A look holds its turn while it reads the PDF from the
600
682
  store, for at most `ingestTimeoutMs` (2 minutes by default). Past it, the turn goes back and the
601
- model is told the file could not be read in time. The read itself goes on: give your store's
602
- `getOriginal` a time limit of its own, shorter than that, when it reads over a network.
683
+ model is told the file could not be read in time. Since 0.10.0 the read of the original is a store
684
+ call within `storeTimeoutMs` (30 s by default), which fails it first: the read itself goes on, and
685
+ counts as stuck until it ends ([A store that stops answering](#a-store-that-stops-answering)).
603
686
  For the documents of users you do not trust, do not offer `view_pages` (`viewPages: false`), or keep
604
687
  no PDF originals. To offer it anyway, run each of their questions, the whole tool loop, in a process
605
688
  you fork, with its own heap and memory limits. What the model is told when pages cannot be shown,
@@ -624,15 +707,25 @@ with `FileDocumentStore`, since removing a file that another sweep just removed
624
707
  each server then lists the whole directory (with `scopes`, every chat's folder) and reads every
625
708
  metadata file. Run it from one server, or take a lease first (a document in MongoDB with an expiry
626
709
  that one server holds at a time). A job of its own runs as the user of the servers, or in their
627
- group with the modes above. Give it the options of the servers' store:
710
+ group with the modes above.
711
+
712
+ **On a network volume**, run it from one pod only, a Kubernetes CronJob for example, not from the
713
+ pods that answer users. `sweepConcurrency` file calls run at once (16 by default), and on a volume
714
+ that hangs each holds a thread of the pool ([A store that stops answering](#a-store-that-stops-answering)):
715
+ set it to at most a quarter of the pool, 8 with `UV_THREADPOOL_SIZE=32`. A sweep has no time limit
716
+ by default, since a sweep of a large volume may take long, and it never counts as a stuck call:
717
+ `sweepTimeoutMs` (new in 0.10.0) gives up on one that takes longer, with a `DocumentStoreError` of
718
+ code `"ETIMEDOUT"`, while the sweep itself goes on. While the process has `maxStuckStoreCalls`
719
+ calls stuck, a sweep is refused at once, as other store calls are. Give it the options of the
720
+ servers' store:
628
721
 
629
722
  ```ts
630
723
  // sweep.ts: run every hour by a scheduled job (cron, a Kubernetes CronJob, Cloud Scheduler).
631
724
  import { createLargeFiles, FileDocumentStore } from "llm-large-files";
632
725
 
633
- // The options of the servers' store: here, a folder per user and chat.
634
- const store = new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents", { scopes: { depth: 2 } });
635
- const files = createLargeFiles({ store });
726
+ // The options of the servers' store: here, a folder per user and chat. Run with UV_THREADPOOL_SIZE=32.
727
+ const store = new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents", { scopes: { depth: 2 }, sweepConcurrency: 8 });
728
+ const files = createLargeFiles({ store, sweepTimeoutMs: 30 * 60 * 1000 });
636
729
  const removed = await files.sweep();
637
730
  console.log(`Removed ${removed} expired documents.`);
638
731
  ```