llm-large-files 0.8.2 → 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 (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  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 +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
@@ -0,0 +1,472 @@
1
+ # Upgrading to 0.10
2
+
3
+ This page takes an application from 0.9.0 to 0.10.0. Most applications change no code: read
4
+ [Requirements](#requirements), [Does my code compile?](#does-my-code-compile),
5
+ [The one cache miss](#the-one-cache-miss) and [Behavior to check](#behavior-to-check). The other
6
+ sections carry the Hebrew chatbot of the 0.9 guide over, and cover loops of your own, Vertex AI,
7
+ servers on a shared volume and rolling deploys. Every change is in the
8
+ [changelog](../CHANGELOG.md).
9
+
10
+ 0.10.0 is about counts that are right and a cost that is bounded. Tables sent whole get exact
11
+ counts, files sent whole get line numbers, and every question has a ceiling on input tokens. The
12
+ text sent to the model changes on purpose, all at once, so each chat with files misses the
13
+ provider's prompt cache once at the upgrade.
14
+
15
+ ## Contents
16
+
17
+ - [Requirements](#requirements)
18
+ - [Does my code compile?](#does-my-code-compile)
19
+ - [The one cache miss](#the-one-cache-miss)
20
+ - [Behavior to check](#behavior-to-check)
21
+ - [The worked example](#the-worked-example)
22
+ - [Loops of your own](#loops-of-your-own)
23
+ - [Vertex AI controls](#vertex-ai-controls)
24
+ - [Operations on a shared volume](#operations-on-a-shared-volume)
25
+ - [Rolling deploys](#rolling-deploys)
26
+ - [New and optional](#new-and-optional)
27
+
28
+ ## Requirements
29
+
30
+ - **Unchanged:** Node.js 22.12 or later, `@types/node` 22 or later, and the optional dependencies
31
+ `unpdf` `^1.4.0 || ^2.0.0`, `jszip` `^3.10.0` and `@cantoo/pdf-lib` `^2.11.1`. The entry points
32
+ are the same six.
33
+ - **What a store holds is unchanged.** `DocumentMeta` keeps `metaVersion: 1`, `ToolTurn` keeps
34
+ `version: 1`, and the files of `FileDocumentStore` keep their names and format. The store
35
+ interface has no new method. A server of 0.9 reads what 0.10.0 writes, and the reverse.
36
+ - **What you store is unchanged.** The `toolTurns` of a result have 0.9's shape (`version: 1`),
37
+ and a result gives nothing new to store. A schema written for 0.9 needs no change.
38
+
39
+ ## Does my code compile?
40
+
41
+ Most code does. Every new option and field is optional, and no export was removed or renamed.
42
+ These do not compile:
43
+
44
+ | Code of yours | The error | What to write |
45
+ |---|---|---|
46
+ | A `switch` over `NoticeCode` with a `never` check, or a `Record<NoticeCode, …>` | Two new members: `"answer_filtered"`, `"answer_cut"` | Add them; a `switch` can end in a `default` instead |
47
+ | The same over `ToolOutcome` | A new member: `"redacted"` | Add it |
48
+ | The same over `ModelReply["finish"]` or the `finish` of a `request.end` event | A new member: `"other"`, which the new `AskResult.finish` has too | Add it |
49
+ | Code that reads `owner`, `scope`, `sha256`, `original` or `metaVersion` of a document in the plan of `run.finish` or `run.error` (`EventResult.plan`) (TS2339) | Its metas are `Omit<DocumentMeta, …>` of those fields, and `eventResults: true` leaves them out at run time too | Read them from `AskResult.plan` |
50
+ | A mock typed `ReturnType<typeof createLargeFiles>`, or a variable whose type was inferred from `createLargeFiles` and that you later give a `LargeFiles` of your own (TS2322) | `createLargeFiles` returns `CreatedLargeFiles`, whose `stats()` and `toolsFor()` are required | Type it `LargeFiles` |
51
+ | A `DocumentHandlers` made by hand, such as a mock (TS2741) | `DocumentHandlers` has a required `stats()` | Add `stats`, or type the mock as the part you use |
52
+ | A `LargeFiles` of your own with a member named `stats` or `toolsFor` of another type (TS2322, TS2416) | `LargeFiles` has optional methods of those names | Rename yours |
53
+ | A value typed `Parameters<typeof vertexAi>[0]` whose `project` you read as a string, or whose `accessToken` you call with no argument (TS2322, TS2554) | `vertexAi` takes `VertexAiOptions`, a union of the token form and express mode (`apiKey`), and its token function is typed with its `{ refresh }` argument | Type it `Extract<VertexAiOptions, { project: string }>`, and call `accessToken({ refresh: false })` |
54
+ | A subclass of `UsageMeter` whose `add` takes a parameter of its own after `usage` (TS2416) | `add(model, usage, estimatedInputTokens?)` takes that place | Put yours after it |
55
+
56
+ Code that compiles and still needs a look:
57
+
58
+ - **An adapter of your own:** `finish` may now be `"other"`, for a reason that asking again does not
59
+ mend ([How the reply ended](./guides/own-adapter-and-loop.md#how-the-reply-ended-finish)).
60
+ - **A `LargeFiles` of your own:** `stats`, `toolsFor` and `PreparedContext.toolable` are optional.
61
+ `askWithFiles` passes `numberInline` and `inlineTables` to its `prepare`. A `prepare` written for
62
+ 0.9 leaves them aside: its blocks are sent as it made them, with no citation line, and its tables
63
+ get no tools, as it gives no `toolable`.
64
+ - **An extractor of your own** that wraps the built-in PDF extractor: pass `headings` on to get the
65
+ new PDF outline ([PDF outline](#a-pdf-outline-from-type-sizes)).
66
+ - **Results built by hand:** `finish` and `citations` are optional.
67
+ - **`askGemini`'s options** are now `Omit<AskOptions, "model" | "explorer" | "messages">` with
68
+ `GeminiOwnOptions`. No field was removed, and every option of `askWithFiles` now reaches the
69
+ loop.
70
+
71
+ ## The one cache miss
72
+
73
+ A provider's prompt cache serves the start of a request it saw before, byte for byte. 0.10.0
74
+ changes the text it sends for a chat with files, so the first request of each such chat after the
75
+ upgrade has a new start, and pays its full input price once. What changes:
76
+
77
+ - Files sent whole are numbered (`12| `), so answers can cite their lines. When no file is
78
+ searched, the system text gets the line `Cite line numbers like (report.docx L12).`
79
+ - A table sent whole gets three tool declarations (`search_document`, `read_document` and
80
+ `aggregate_table`), its `document_id` in the first line of its block, and a line of the system
81
+ text that says to count with them.
82
+ - `analyze_whole_document` is declared with two more arguments, `output` and `labels`.
83
+ - The request for the answer after files shown in full asks for an answer from those files and
84
+ what the tools returned, with line citations. 0.9's named only what the tools returned.
85
+ - On a card, a size between 999,500 and 999,999 tokens reads "1.0M"; on a card and in
86
+ `get_document_overview`, a size between 1,048,064 and 1,048,575 bytes reads "1 MB", and so do the
87
+ error messages that print such a size (upload and text limits, `view_pages`).
88
+
89
+ **Why one miss.** All these changes ship in one release, so a chat misses once, not once a
90
+ version. **After the miss,** the cache works across questions as in 0.9
91
+ ([Prompt caching](./guides/costs-and-limits.md#prompt-caching)). A follow-up still differs from
92
+ its first stored round, which goes back as its calls: the cache can serve the system text, the
93
+ tools and the turns before that round. On the Gemini API with Gemini 3.8 Flash, such a follow-up
94
+ kept only the system text and tools in the cache (33.7% of a 7K request, 15.7% of a 15K one, 9 of
95
+ 9) ([Measurements](./measurements.md#the-live-session-on-the-gemini-api)). The cache share is
96
+ reported in `usage.cachedInputTokens`, not promised: the provider decides what it serves.
97
+
98
+ ### Going back to 0.9's text
99
+
100
+ Each of these gives 0.9's bytes for what it covers, for this version:
101
+
102
+ | Option | Gives back |
103
+ |---|---|
104
+ | `inlineTables: "text"` | Tables sent whole without tools: one request, counts made by eye |
105
+ | `numberInline: false` | Files sent whole without line numbers |
106
+
107
+ With both, the requests are still not 0.9's. These have no way back:
108
+
109
+ - the `whole_file` hint of a `read_document` result cut short, and the `filter_note` of
110
+ `aggregate_table`;
111
+ - the declaration of `analyze_whole_document`, and the prompts of its part reads and merges (M8);
112
+ - the card sizes "1.0M" and "1 MB".
113
+
114
+ ## Behavior to check
115
+
116
+ ### A ceiling on input tokens, and 2 whole-file reads
117
+
118
+ A question that sets no `limits.inputTokens` has a ceiling: the larger of `DEFAULT_INPUT_TOKENS`
119
+ (1,000,000) and `toolTurns` times the estimate of its first request, plus room for its whole-file
120
+ reads. Before each tool request the loop looks ahead: when what was spent, the next tool request
121
+ and the answer would pass it, the next request is the answer. A request that reports no input
122
+ counts by its estimate (`usage.estimatedInputTokens`, `usage.unmeasuredRequests`). A question makes
123
+ at most 2 whole-file reads in all (`wholeReadsPerQuestion`).
124
+
125
+ **Who:** questions with long tool loops, or several whole-file reads.
126
+ **What to do:** nothing. `limits: { inputTokens: Infinity, wholeReadsPerQuestion: Infinity }`
127
+ gives 0.9's rules ([The default ceiling](./guides/costs-and-limits.md#the-default-ceiling)).
128
+
129
+ ### Tables sent whole get tools, and files sent whole are numbered
130
+
131
+ In `askWithFiles` and `askGemini`, a table sent whole (a CSV, an XLSX workbook, or a DOCX, PPTX,
132
+ PDF, HTML or Markdown file with a table of at least 3 `| cell |` rows) gets `search_document`,
133
+ `read_document` and `aggregate_table`, and the question runs the tool loop. Counts and sums are
134
+ then exact. Files sent whole are numbered, about 8% to 16% more tokens each, and a file at the edge
135
+ of `inlineTokens` may become a card.
136
+
137
+ What a question over a table costs:
138
+
139
+ - **No count:** one request when the model answers at once, a little larger (about 1,500 tokens of
140
+ declarations and a guide line).
141
+ - **A count:** 2 or 3 requests (live, a median of 2 on both models), each sending the table again.
142
+ The later requests start as the first did, so an implicit cache bills most of them at the cached
143
+ price.
144
+ - **At most:** about `toolTurns` times the first request, bounded by the ceiling: about 1.5M input
145
+ tokens for a CSV of 3,000 invoices.
146
+ - **Live, on the eval's cases** shared with 0.9.0: about 2.3 to 2.4 times 0.9.0's input tokens.
147
+ Counts were right in 24 of 24 on Gemini 3.5 Flash-Lite and 3.8 Flash.
148
+ - **Gemini 3.5 Flash-Lite looks rows up with a tool**, even when the table is shown in full: 21 of
149
+ 39 questions with no count took one request (3.8 Flash: 38 of 39). A lookup then takes 2
150
+ requests, each with the table. The lookups are exact; 0.9.0 got some wrong by eye. This is
151
+ recorded, not tuned.
152
+ - **Limits sized for 0.9's one request** (`toolTurns: 1`, `requests: 1`, an `inputTokens` between
153
+ one and two requests with the table) leave no tool turn: the question makes 0.9's one request,
154
+ without tools.
155
+
156
+ **Who:** chats whose files are sent whole.
157
+ **What to do:** nothing, or `inlineTables: "text"` for 0.9's cost and `numberInline: false` for
158
+ 0.9's blocks ([Tables sent whole](./guides/costs-and-limits.md#tables-sent-whole)).
159
+
160
+ ### Evidence lists the files sent whole first
161
+
162
+ `AskResult.evidence` starts with one entry for each file sent whole:
163
+ `{ tool: "inline", documentId, document, lines: [[1, n]], whole: true }`, with no `callId`.
164
+
165
+ **Who:** code that counts tool calls from evidence, or maps it to `tool.end`.
166
+ **What to do:** skip the entries without a `callId`.
167
+
168
+ ### Store calls time out at 30 s
169
+
170
+ A `getMeta`, a read of a text, its index or its original, or a `delete` that does not end within
171
+ `storeTimeoutMs` (30 s) fails with a `DocumentStoreError` of code `"ETIMEDOUT"` (503, to retry).
172
+ In a question, also inside a tool call or a part of a whole-file read, it ends the question with
173
+ `run.error`. While `maxStuckStoreCalls` calls of the process are stuck past their limit, store
174
+ calls fail at once with `"STORE_STUCK"` (503).
175
+
176
+ **Who:** servers whose store is a network volume or a remote service.
177
+ **What to do:** set `UV_THREADPOOL_SIZE=32` on servers with a network volume, and see
178
+ [Operations on a shared volume](#operations-on-a-shared-volume). `storeTimeoutMs: 0` sets no
179
+ limit.
180
+
181
+ ### Transient errors are 503, and Gemini's errors in a stream are retried
182
+
183
+ - `ETIMEDOUT`, `ECONNRESET`, `ECONNREFUSED`, `EPIPE`, `EAI_AGAIN`, `EAGAIN`, `EBUSY`, `EMFILE`,
184
+ `ENFILE`, `ESTALE`, `EHOSTUNREACH` and `ENETUNREACH` are 503 with `Retry-After: 5` in
185
+ `errorInfoOf` and the upload handlers; `ENOSPC` and `EDQUOT` are 503 with 30 s. They were 500:
186
+ "Upload failed (ETIMEDOUT)." is now a 503. A path upload whose read does not answer within
187
+ `ingestTimeoutMs` is such an `ETIMEDOUT`, not the `IngestError` `"timeout"` (422).
188
+ - A Gemini error inside a stream, or in a reply of HTTP 200, with no numeric code gets the status
189
+ of its `google.rpc` name (`UNAVAILABLE` 503, `RESOURCE_EXHAUSTED` 429, `DEADLINE_EXCEEDED` 504),
190
+ and a transient one is sent again up to `retry.retries` times, unless text was already shown. A
191
+ daily quota is still not sent again.
192
+ - A part read that runs out of time is a `ModelRequestError` of kind `"timeout"` and status 0 in
193
+ every adapter, sent again once after the first wait of `retry`. `timeoutMs: 0` sets no limit;
194
+ in 0.9 it aborted every part read at once.
195
+
196
+ **Who:** pages that word errors, and code that reads `status`.
197
+ **What to do:** tell users to try again when `errorInfoOf(error).retryable` is true
198
+ ([Transient errors](./guides/errors-and-reliability.md#transient-errors-a-store-or-a-disk-that-does-not-answer)).
199
+
200
+ ### Filtered and cut answers
201
+
202
+ A reply that a filter stopped part-way was an answer like any other in 0.9. Now `result.finish`
203
+ says how the answer ended. An `answer_filtered` or `answer_cut` notice comes before `run.finish`.
204
+ A reply ended by `"filtered"` or `"other"` is not asked for again: 2 requests over a searched file,
205
+ where 0.9 made 4. Gemini's `MODEL_ARMOR` and the image filters new since 0.9
206
+ (`IMAGE_PROHIBITED_CONTENT`, `IMAGE_RECITATION`, `IMAGE_OTHER`) count as `"filtered"`, as
207
+ `IMAGE_SAFETY` did; `OTHER`, `LANGUAGE` and four more as `"other"`. `MALFORMED_RESPONSE` is now `"malformed_call"`: the turn is
208
+ asked for once more.
209
+
210
+ **Who:** every chat page.
211
+ **What to do:** switch on `answerInfoOf(result)` for the message to show. With
212
+ `filteredAnswer: "drop"`, a filtered answer is dropped, and the notice has `discardText: true`
213
+ when its text was already streamed: take it back on the page
214
+ ([Filtered and cut answers](./guides/errors-and-reliability.md#filtered-and-cut-answers)).
215
+
216
+ ### A malformed call on the last turn gets a closing request
217
+
218
+ On the last tool turn, a reply whose tool call could not be read was taken for the answer, its
219
+ remark included (LLF-048). The loop now asks for the answer.
220
+
221
+ **Who:** tests that count requests.
222
+ **What to do:** expect one request more in that case.
223
+
224
+ ### The loop answers unknown tools itself
225
+
226
+ A call of an unknown tool is answered by the loop: "Unknown tool “x”. The tools are: …", with
227
+ outcome `"refused"` and no `onActivity` line. In 0.9 the tool set answered it, with outcome
228
+ `"error"`.
229
+
230
+ **Who:** tests that compare results or events whole, and code that counts outcomes.
231
+ **What to do:** update them.
232
+
233
+ ### Event plans without owner data
234
+
235
+ With `eventResults: true`, the plan of `run.finish` and `run.error` no longer holds `owner`,
236
+ `scope`, `sha256`, `original` or `metaVersion`, and its type says so.
237
+
238
+ **Who:** code that reads those fields from events.
239
+ **What to do:** read them from `AskResult.plan`.
240
+
241
+ ### A PDF outline from type sizes
242
+
243
+ A PDF ingested from 0.10.0 on, whose text gives fewer than 3 headings, gets an outline from its
244
+ lines set at least 15% larger than its body, when 3 or more of them are found in its text. That is
245
+ most PDFs with headings in larger type, Hebrew ones included: Hebrew has no capitals, and pdf.js
246
+ gives no blank lines, so the text rules found none. Its card gains an "Outline" block,
247
+ `get_document_overview` lists it, and search hits gain `section`. A PDF with a title alone keeps the
248
+ card and hits of 0.9. Bold headings at body size, Word's Heading 3 and month-name dates set large
249
+ are among what it misses or takes wrongly ([PDF outline](./guides/pdfs.md#pdf-outline)).
250
+
251
+ **Who:** apps with PDF uploads, and extractors of your own that wrap the built-in PDF extractor.
252
+ **What to do:** nothing for stored documents: they keep their outline until they are ingested
253
+ again (with your ID, `ifExists: "replace"`); `metaVersion` stays 1. A wrapper that returns only
254
+ `text` and `pages` keeps 0.9's outline: return `{ ...extracted, text }` to pass `headings` on.
255
+
256
+ ## The worked example
257
+
258
+ The Hebrew chatbot of [the 0.9 guide](./upgrading-0.9.md#a-worked-example-a-hebrew-chatbot-on-gemini-mongodb-and-a-shared-volume)
259
+ answers with Gemini on Vertex AI, keeps its chats in MongoDB (one record per chat, one per
260
+ question), and stores its files on a shared volume with a folder per user and chat. Its
261
+ `documents.ts` and its records do not change: each question's record keeps the question's text,
262
+ its `toolTurns` and its answer, as in 0.9. Its `ask.ts` changes in four places:
263
+
264
+ - the token function takes `{ refresh }`, and fetches a new token after a 401;
265
+ - `body` puts billing labels on every request;
266
+ - `filteredAnswer: "drop"` drops a filtered answer;
267
+ - `answerInfoOf` gives the Hebrew message for an answer that is not complete.
268
+
269
+ ```ts
270
+ // ask.ts: a question of a chat on Vertex AI, with Hebrew words for an answer cut or filtered.
271
+ import { GoogleAuth } from "google-auth-library";
272
+ import { answerInfoOf, errorInfoOf, partialResultOf, type AnswerInfo, type ChatTurn, type ErrorInfo, type ToolTurn } from "llm-large-files";
273
+ import { askGemini, vertexAi } from "llm-large-files/gemini";
274
+ import { files, scopeOf, sessions, turns, type TurnRecord } from "./documents.js";
275
+
276
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
277
+
278
+ // After a 401, { refresh: true }: the token in the cache was refused, and a new one is fetched.
279
+ async function accessToken({ refresh }: { refresh: boolean }): Promise<string> {
280
+ const client = await auth.getClient();
281
+ if (refresh) client.setCredentials({ ...client.credentials, expiry_date: 1 });
282
+ const { token } = await client.getAccessToken();
283
+ if (!token) throw new Error("No access token from the application default credentials.");
284
+ return token;
285
+ }
286
+
287
+ const endpoint = vertexAi({ project: process.env.GOOGLE_CLOUD_PROJECT!, location: "global", model: "gemini-3.8-flash", accessToken });
288
+
289
+ /** The messages of the next question: each earlier question, its tool rounds, its answer. */
290
+ function historyOf(earlier: TurnRecord[], question: string): Array<ChatTurn | ToolTurn> {
291
+ return [
292
+ ...earlier.flatMap((turn): Array<ChatTurn | ToolTurn> => [
293
+ { role: "user", text: turn.question },
294
+ ...turn.toolTurns,
295
+ ...(turn.answer !== undefined ? [{ role: "assistant" as const, text: turn.answer }] : []),
296
+ ]),
297
+ { role: "user", text: question },
298
+ ];
299
+ }
300
+
301
+ export type Answer = { status: number; text?: string; note?: string; error?: string; retryAfterMs?: number };
302
+
303
+ export async function ask(userId: string, sessionId: string, question: string, signal: AbortSignal): Promise<Answer> {
304
+ const session = await sessions.findOne({ _id: sessionId, userId });
305
+ if (!session) return { status: 404, error: "השיחה הזו כבר לא קיימת." };
306
+ const earlier = await turns.find({ sessionId }).sort({ index: 1 }).toArray();
307
+ const asked = { sessionId, index: earlier.length, question, createdAt: new Date() };
308
+ try {
309
+ const result = await askGemini({
310
+ files,
311
+ endpoint,
312
+ body: { labels: { app: "chatbot", team: "hr" } }, // billing labels: never a user ID
313
+ owner: userId,
314
+ scope: scopeOf(userId, sessionId),
315
+ documentIds: session.files.map((file) => file.id),
316
+ messages: historyOf(earlier, question),
317
+ onMissingDocuments: "drop",
318
+ filteredAnswer: "drop",
319
+ signal,
320
+ });
321
+ await turns.insertOne({ ...asked, toolTurns: result.toolTurns, ...(result.answered ? { answer: result.text } : {}) });
322
+ if (result.missing?.length) {
323
+ await sessions.updateOne({ _id: sessionId, userId }, { $pull: { files: { id: { $in: result.missing } } } });
324
+ }
325
+ const info = answerInfoOf(result);
326
+ if (info.complete) return { status: 200, text: result.text };
327
+ // A cut answer has text worth reading: the message goes under it.
328
+ return result.answered && result.text ? { status: 200, text: result.text, note: hebrew(info) } : { status: 200, text: hebrew(info) };
329
+ } catch (error) {
330
+ const partial = partialResultOf(error);
331
+ if (partial) await turns.insertOne({ ...asked, toolTurns: partial.toolTurns });
332
+ console.error("A question failed", error);
333
+ const info = errorInfoOf(error);
334
+ // errorWords is the `hebrew` function of the 0.9 guide: the words for each kind of error.
335
+ return { status: info.status, error: errorWords(info), ...(info.retryAfterMs !== undefined ? { retryAfterMs: info.retryAfterMs } : {}) };
336
+ }
337
+ }
338
+
339
+ declare function errorWords(info: ErrorInfo): string;
340
+
341
+ /** Why the answer is not complete, in Hebrew. The whole table is in the errors guide. */
342
+ function hebrew(info: AnswerInfo): string {
343
+ switch (info.reason) {
344
+ case "filtered": return "התשובה נעצרה על ידי מסנן התוכן, ולכן היא לא מוצגת.";
345
+ case "cut": return "התשובה נקטעה כי הייתה ארוכה מדי. אפשר לבקש את ההמשך, או לשאול שאלה ממוקדת יותר.";
346
+ case "blocked": return "אי אפשר לענות על השאלה הזו. נסו לנסח אותה אחרת.";
347
+ case "language": return "לא הצלחנו לענות בשפה של השאלה. נסו לנסח אותה שוב.";
348
+ case "no_answer": return "לא התקבלה תשובה הפעם. נסו לשאול שוב, או לשאול בצורה מדויקת יותר.";
349
+ default: return "משהו השתבש בזמן כתיבת התשובה. נסו שוב.";
350
+ }
351
+ }
352
+ ```
353
+
354
+ - **`filteredAnswer: "drop"`.** A filtered answer comes back with `answered: false` and no text,
355
+ so the record keeps no answer. When the answer was streamed, the `answer_filtered` notice has
356
+ `discardText: true`: the page takes back what it showed
357
+ ([Filtered and cut answers](./guides/errors-and-reliability.md#filtered-and-cut-answers)).
358
+ - **`body` labels** reach the project's billing export. Label by app, team or feature, never by
359
+ user.
360
+ - **The chat misses the cache once**, at its first question after the upgrade: its files are
361
+ numbered from then on. A follow-up still differs from its first stored round, as in 0.9
362
+ ([The one cache miss](#the-one-cache-miss)).
363
+
364
+ ## Loops of your own
365
+
366
+ `files.prepare()` keeps 0.9's plan, blocks and `instruction`, names included, unless you pass
367
+ `numberInline` or `inlineTables`. With `inlineTables: "tools"` it also returns `toolable`.
368
+
369
+ - **Line numbers and tables with tools:** pass `numberInline: true` and `inlineTables: "tools"`,
370
+ and give the tools the files of `prepared.toolable` too, with the IDs of the files sent whole as
371
+ `ToolOptions.inline` and the tools to declare as `ToolOptions.declare` (`search_document`,
372
+ `read_document` and `aggregate_table` for those tables). `declarationsFor(names)` gives the
373
+ declarations of those tools, to plan the size of a request
374
+ ([Numbered lines and tables sent whole](./how-it-works.md#numbered-lines-and-tables-sent-whole)).
375
+ - **Store timeouts end the call.** `execute` and `executeWithFiles` throw a `DocumentStoreError`
376
+ of code `"ETIMEDOUT"` or `"STORE_STUCK"`, where they returned an error result. End the question
377
+ on it.
378
+ - **`ToolCallHooks.signal`** stops a call's scans, reads and page looks, and
379
+ `ToolSet.wholeReadsLeft(documentId)` says whether a whole read can still run.
380
+ - **A whole read given `ToolCallLimits.maxRequests`** with more parts than that is refused before
381
+ any request; with enough for its parts, it stops merging at it (`notes_left_out`).
382
+
383
+ ## Vertex AI controls
384
+
385
+ New options of `gemini()` and `askGemini`, each unset by default
386
+ ([Vertex AI and Gemini](./guides/vertex-and-gemini.md#fields-of-your-own-safety-settings-labels-and-more)):
387
+
388
+ | Option | What it does |
389
+ |---|---|
390
+ | `body` | Fields merged last into every chat request: `safetySettings`, `labels`, `serviceTier`, `cachedContent` (`GeminiRequestFields`) |
391
+ | `explorerBody` | The same for the explorer, when it needs other fields (`askGemini`) |
392
+ | `analysisBody` | A function of `maxOutputTokens`, merged last into each part read |
393
+ | `functionCallingMode` | `"VALIDATED"` has Gemini check each call against its declaration; `"AUTO"` by default. Not measured live |
394
+ | `timeoutMs` | The time limit of a part read: 180,000 by default, 0 for none |
395
+ | `answerWithoutTools` | `"omit"` (the default) or `"mode_none"` for the request of the answer. Live, `"mode_none"` closings were never served from the cache where no earlier closing existed, and cost about 1.8K more input tokens: keep `"omit"` |
396
+
397
+ And of `vertexAi()`:
398
+
399
+ - **`accessToken({ refresh })`**: after a 401, the request is sent once more with
400
+ `{ refresh: true }`, so fetch a new token then. A second 401 is the error
401
+ ([Access tokens](./guides/vertex-and-gemini.md#access-tokens-for-vertex-ai)).
402
+ - **`headers`** and **`host`**: headers of your own, and another host (a private endpoint).
403
+ - **`apiKey`**: Vertex AI express mode, with no project or token.
404
+
405
+ Before you set them:
406
+
407
+ - **Labels reach the billing export** of the project, and everyone who reads it. Never put a user
408
+ ID, an email or other personal data in them.
409
+ - **`body` changes the bytes of every request**: the first request after you set it misses the
410
+ cache once.
411
+
412
+ ## Operations on a shared volume
413
+
414
+ - **`storeTimeoutMs`** (30,000): the time limit of each store call. Size it above the slowest
415
+ healthy call: the read of the largest text loaded whole (2 MB by default) or of the largest
416
+ original a page look reads, at the volume's busiest.
417
+ - **`UV_THREADPOOL_SIZE=32`** in the environment of each server that uses a network volume. A
418
+ disk call that does not answer holds one of libuv's threads until it does; with the default 4,
419
+ four stuck calls froze every file call and DNS look-up of the process. Check that the value
420
+ reaches the process: an empty value is a pool of 1 thread.
421
+ - **`maxStuckStoreCalls`**: half the pool by default (2 with 4 threads, 16 with 32). At the limit,
422
+ store calls fail at once with `"STORE_STUCK"`, so the threads left keep serving.
423
+ - **`files.stats()` and `handlers.stats()`** read counters only, with no store call. Alert on
424
+ `stuckStoreCalls` above 0. Fail readiness on local saturation (`ingests.waiting`,
425
+ `handlers.stats().uploadsInFlight`), and on stuck calls only when they stay at the limit for 60 s or more:
426
+ all pods share one volume, and a probe that fails at once takes every pod out at once.
427
+ - **The sweep:** run it from one pod, or from a scheduled job. `sweepTimeoutMs` bounds it; it never
428
+ counts as stuck, but is refused while too many calls are.
429
+
430
+ The probe, the table of stuck calls and the alerts:
431
+ [A store that stops answering](./guides/deployment.md#a-store-that-stops-answering).
432
+
433
+ ## Rolling deploys
434
+
435
+ Servers of 0.9 and 0.10 can share a store and answer the same chats. What 0.10.0 stores is what
436
+ 0.9 stores, in both directions, so nothing fails. But the two versions send different text (the
437
+ numbered blocks, the declarations), so a chat answered by both versions in turn misses the prompt
438
+ cache on every switch.
439
+
440
+ - **Deploy every server at once**, or route each chat to one version until the rollout ends (by
441
+ chat ID at the load balancer, for example).
442
+ - **Documents** need nothing: their metadata and files are those of 0.9.0. A PDF keeps the outline
443
+ it was ingested with.
444
+ - **Run the sweep from a server of 0.10.0**: its time limit and stuck-call limit apply there.
445
+
446
+ More on servers of two versions: [Deployment](./guides/deployment.md#servers-of-two-versions).
447
+
448
+ ## New and optional
449
+
450
+ - **How an answer ended:** `AskResult.finish`, `answerInfoOf`, `filteredAnswer`
451
+ ([Errors and reliability](./guides/errors-and-reliability.md#filtered-and-cut-answers)).
452
+ - **Citations checked:** `AskResult.citations` and `checkCitations`, Hebrew forms included
453
+ ([ask](./reference/ask.md#citationcheck)).
454
+ - **Tool results before the model sees them:** `onToolResult`
455
+ ([Security](./security.md#tool-results-ontoolresult)).
456
+ - **Limits:** `wholeReadsPerQuestion`, `DEFAULT_INPUT_TOKENS`, `usage.estimatedInputTokens`
457
+ ([Costs and limits](./guides/costs-and-limits.md#the-limits-of-a-question)).
458
+ - **Tables and line numbers:** `inlineTables`, `numberInline`
459
+ ([Costs and limits](./guides/costs-and-limits.md#tables-sent-whole)).
460
+ - **Items read whole:** `analyze_whole_document` with `output: "items"` and `labels`
461
+ ([tools](./reference/tools.md#items-output-items)).
462
+ - **Gemini and Vertex AI:** `body`, `analysisBody`, `explorerBody`, `functionCallingMode`,
463
+ `timeoutMs`, `answerWithoutTools`, `vertexAi({ headers, host, apiKey })` and
464
+ `accessToken({ refresh })` ([gemini](./reference/gemini.md#geminiownoptions)).
465
+ - **Other providers:** response IDs from every adapter.
466
+ - **Operations:** `storeTimeoutMs`, `sweepTimeoutMs`, `maxStuckStoreCalls`, `AccessOptions.signal`,
467
+ `files.stats()`, `handlers.stats()`, `files.toolsFor()`
468
+ ([library](./reference/library.md#largefilesoptions)).
469
+ - **PDFs:** `ExtractedText.headings` ([PDF outline](./guides/pdfs.md#pdf-outline)).
470
+ - **Loops of your own:** `PrepareOptions.numberInline` and `inlineTables`,
471
+ `PreparedContext.toolable`, `ToolOptions.declare` and `inline`, `declarationsFor`, `ToolName`,
472
+ `ToolCallHooks.signal` ([library](./reference/library.md#preparedcontext)).