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,37 @@
1
+ import { estimateMerges } from "./map-reduce.js";
2
+ import type { Budget, DocumentMeta } from "./types.js";
3
+ /** The merges of notes a read makes, worked out from the rounds of `analyzeWholeDocument` (src/map-reduce.ts). */
4
+ export { estimateMerges };
5
+ /**
6
+ * The digits of the line numbers 1 to `lines`, written out: what the numbers take in the prompts of
7
+ * the parts. `estimateParts` (src/plan.ts) counts them the same way.
8
+ */
9
+ export declare function lineNumberDigits(lines: number): number;
10
+ /** What a whole-file read costs. */
11
+ export type WholeReadCost = {
12
+ /** The input tokens of all its requests, in the model's own tokens (the library's estimate times `scale`). */
13
+ inputTokens: number;
14
+ /** All its requests: the parts, the merges of their notes, and the answer of the read. */
15
+ requests: number;
16
+ /** The part reads among them. */
17
+ parts: number;
18
+ /** The merges of notes among them. */
19
+ merges: number;
20
+ };
21
+ /**
22
+ * The input tokens and requests of a whole-file read of `meta`, with the `budget` of the question
23
+ * and the `scale` of the model that reads it (`capabilities.tokenScale`). The parts are
24
+ * `estimateParts`'s; each sends its lines numbered (the document's tokens, 1.2 tokens a digit of
25
+ * the line numbers and 1.5 a line) with its system text, task and rules, and each after the first
26
+ * of a file with an outline the heading it starts under (`PART_HEADING_TOKENS`).
27
+ * The merges are `estimateMerges`'s, for notes as long as the output limit allows, and the answer
28
+ * of the read is one request more. It is a price before the read: what a read sends is usually
29
+ * less, as notes are shorter than the limit, and not every part starts under a heading. NaN for
30
+ * metadata that does not give its size.
31
+ *
32
+ * `output` "items" (a read that lists items, new in 0.10.0) is the parts alone, each with the
33
+ * longer rules of a list: no merge and no answer. A part read again in halves, when its list does
34
+ * not fit the output limit, is not in the price, as a part halved by an answer read is not.
35
+ */
36
+ export declare function wholeReadCost(meta: Pick<DocumentMeta, "estimatedTokens" | "lines" | "textBytes" | "jsonBytes"> & Partial<Pick<DocumentMeta, "format" | "outline">>, budget: Budget, scale: number, output?: "answer" | "items"): WholeReadCost;
37
+ //# sourceMappingURL=whole-cost.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"whole-cost.d.ts","sourceRoot":"","sources":["../src/whole-cost.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAwG,MAAM,iBAAiB,CAAC;AAEvJ,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAEvD,kHAAkH;AAClH,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1B;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAItD;AAED,oCAAoC;AACpC,MAAM,MAAM,aAAa,GAAG;IAC1B,8GAA8G;IAC9G,WAAW,EAAE,MAAM,CAAC;IACpB,0FAA0F;IAC1F,QAAQ,EAAE,MAAM,CAAC;IACjB,iCAAiC;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,sCAAsC;IACtC,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,iBAAiB,GAAG,OAAO,GAAG,WAAW,GAAG,WAAW,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE,QAAQ,GAAG,SAAS,CAAC,CAAC,EACrI,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,MAAM,GAAE,QAAQ,GAAG,OAAkB,GACpC,aAAa,CAUf"}
@@ -0,0 +1,46 @@
1
+ // What a whole-file read (`analyze_whole_document`) costs, before it starts: the input tokens of
2
+ // all its requests, and how many requests it makes, from the document's metadata alone. New in
3
+ // 0.10.0, for the ceiling of a question, which prices a read before it lets it run. Internal: not
4
+ // exported from the package.
5
+ import { estimateMerges, ITEMS_FRAME_TOKENS, PART_HEADING_TOKENS, PART_OUTPUT_TOKENS, partsHaveHeadings, REQUEST_FRAME_TOKENS } from "./map-reduce.js";
6
+ import { estimateParts } from "./plan.js";
7
+ /** The merges of notes a read makes, worked out from the rounds of `analyzeWholeDocument` (src/map-reduce.ts). */
8
+ export { estimateMerges };
9
+ /**
10
+ * The digits of the line numbers 1 to `lines`, written out: what the numbers take in the prompts of
11
+ * the parts. `estimateParts` (src/plan.ts) counts them the same way.
12
+ */
13
+ export function lineNumberDigits(lines) {
14
+ let digits = 0;
15
+ for (let width = 1, first = 1; first <= lines; width++, first *= 10)
16
+ digits += (Math.min(lines, first * 10 - 1) - first + 1) * width;
17
+ return digits;
18
+ }
19
+ /**
20
+ * The input tokens and requests of a whole-file read of `meta`, with the `budget` of the question
21
+ * and the `scale` of the model that reads it (`capabilities.tokenScale`). The parts are
22
+ * `estimateParts`'s; each sends its lines numbered (the document's tokens, 1.2 tokens a digit of
23
+ * the line numbers and 1.5 a line) with its system text, task and rules, and each after the first
24
+ * of a file with an outline the heading it starts under (`PART_HEADING_TOKENS`).
25
+ * The merges are `estimateMerges`'s, for notes as long as the output limit allows, and the answer
26
+ * of the read is one request more. It is a price before the read: what a read sends is usually
27
+ * less, as notes are shorter than the limit, and not every part starts under a heading. NaN for
28
+ * metadata that does not give its size.
29
+ *
30
+ * `output` "items" (a read that lists items, new in 0.10.0) is the parts alone, each with the
31
+ * longer rules of a list: no merge and no answer. A part read again in halves, when its list does
32
+ * not fit the output limit, is not in the price, as a part halved by an answer read is not.
33
+ */
34
+ export function wholeReadCost(meta, budget, scale, output = "answer") {
35
+ const parts = estimateParts(meta, budget);
36
+ const lines = Math.max(1, meta.lines);
37
+ // The first part starts at line 1, under no heading.
38
+ const headings = partsHaveHeadings(meta) ? (parts - 1) * PART_HEADING_TOKENS : 0;
39
+ const numbered = meta.estimatedTokens + 1.2 * lineNumberDigits(lines) + 1.5 * lines + headings;
40
+ if (output === "items")
41
+ return { inputTokens: Math.ceil((numbered + parts * ITEMS_FRAME_TOKENS) * scale), requests: parts, parts, merges: 0 };
42
+ const merges = estimateMerges(parts, PART_OUTPUT_TOKENS, budget.mapChunkTokens);
43
+ const tokens = numbered + parts * REQUEST_FRAME_TOKENS + merges.inputTokens + merges.finalTokens + REQUEST_FRAME_TOKENS;
44
+ return { inputTokens: Math.ceil(tokens * scale), requests: parts + merges.requests + 1, parts, merges: merges.requests };
45
+ }
46
+ //# sourceMappingURL=whole-cost.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"whole-cost.js","sourceRoot":"","sources":["../src/whole-cost.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,+FAA+F;AAC/F,kGAAkG;AAClG,6BAA6B;AAC7B,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvJ,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAG1C,kHAAkH;AAClH,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1B;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAAa;IAC5C,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,KAAK,EAAE,KAAK,EAAE,EAAE,KAAK,IAAI,EAAE;QAAE,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;IACrI,OAAO,MAAM,CAAC;AAChB,CAAC;AAcD;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,aAAa,CAC3B,IAAqI,EACrI,MAAc,EACd,KAAa,EACb,SAA6B,QAAQ;IAErC,MAAM,KAAK,GAAG,aAAa,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IAC1C,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;IACtC,qDAAqD;IACrD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC;IACjF,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,GAAG,GAAG,GAAG,gBAAgB,CAAC,KAAK,CAAC,GAAG,GAAG,GAAG,KAAK,GAAG,QAAQ,CAAC;IAC/F,IAAI,MAAM,KAAK,OAAO;QAAE,OAAO,EAAE,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,QAAQ,GAAG,KAAK,GAAG,kBAAkB,CAAC,GAAG,KAAK,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC;IAC9I,MAAM,MAAM,GAAG,cAAc,CAAC,KAAK,EAAE,kBAAkB,EAAE,MAAM,CAAC,cAAc,CAAC,CAAC;IAChF,MAAM,MAAM,GAAG,QAAQ,GAAG,KAAK,GAAG,oBAAoB,GAAG,MAAM,CAAC,WAAW,GAAG,MAAM,CAAC,WAAW,GAAG,oBAAoB,CAAC;IACxH,OAAO,EAAE,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,EAAE,QAAQ,EAAE,KAAK,GAAG,MAAM,CAAC,QAAQ,GAAG,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC;AAC3H,CAAC"}
package/docs/README.md CHANGED
@@ -123,7 +123,8 @@ Each term links to the page that explains it. The defaults and limits are on tho
123
123
  - **Document**: a file after `files.ingest()`: its extracted text, which the tools read by line
124
124
  number, and its metadata (`DocumentMeta`), kept in the store under an ID the library makes
125
125
  (`doc_` and 32 hex characters). It expires after `ttlMs`. The uploaded file itself is kept only
126
- for the formats in `keepOriginals`. See [storage](./guides/storage.md).
126
+ for the formats in `keepOriginals`: in the store, or where your application keeps it (0.9.0). See
127
+ [storage](./guides/storage.md).
127
128
  - **Evidence**: `AskResult.evidence`, one entry for each tool call that showed the model part of a
128
129
  document: which document, and which lines or pages, as ranges (`Evidence`). A whole-file read is
129
130
  marked `whole: true`. Keep it with the answer for citations or an audit trail. See
@@ -223,13 +224,15 @@ One task each, with samples:
223
224
  - [An explorer model](./guides/explorer-model.md): a second, cheaper model that explores the
224
225
  documents while another answers: who does what, what changes for your app, cost, any pair of
225
226
  providers.
226
- - [Web app](./guides/web-app.md): uploads (`createDocumentHandlers`, direct `ingest`, the
227
- browser), answers and progress streamed over server-sent events, cancelling.
227
+ - [Web app](./guides/web-app.md): uploads (`createDocumentHandlers`, its hooks, saving each upload
228
+ in the chat's folder, spooling to disk, direct `ingest`, the browser), answers and progress
229
+ streamed over server-sent events, cancelling.
228
230
  - [Conversations](./guides/conversations.md): the message format, keeping tool turns, history
229
231
  across requests and servers, staying inside the window, converters, pointers for repeated calls,
230
232
  mixing providers.
231
233
  - [Storage](./guides/storage.md): the `DocumentStore` contract and writing your own, the built-in
232
- stores, owners and a layout per user and per session, retention, original files, the cache.
234
+ stores, owners and a layout per user and per session, retention, original files (a copy in the
235
+ store, or the uploads your application keeps), the cache.
233
236
  - [Deployment](./guides/deployment.md): several servers, memory sizing, sweeps, proxies and
234
237
  timeouts for streams, rolling upgrades, Node.js and ESM.
235
238
  - [Errors and reliability](./guides/errors-and-reliability.md): every error and its kind and what
@@ -242,8 +245,9 @@ One task each, with samples:
242
245
  and OCR.
243
246
  - [Your own adapter and loop](./guides/own-adapter-and-loop.md): writing or wrapping a
244
247
  `ModelAdapter`, your own loop with `prepare()` and `tools()`, `parseSseJson`, `withRetry`.
245
- - [Testing an integration](./guides/testing.md): tests without a real model: a scripted model, the
246
- real adapters with a fake `fetch`, errors, expiry and owners, and a few cheap live tests.
248
+ - [Testing an integration](./guides/testing.md): tests without a real model: a scripted model and
249
+ the real adapters with a fake `fetch` (both from `llm-large-files/testing`), errors, expiry and
250
+ owners, and a few cheap live tests.
247
251
 
248
252
  ## Reference by module
249
253
 
@@ -260,7 +264,8 @@ import from.
260
264
  | `llm-large-files/gemini` | [Gemini](./reference/gemini.md) | `askGemini`, `gemini()`, `geminiApi()`, `vertexAi()` and the other Gemini exports |
261
265
  | `llm-large-files/openai` | [OpenAI-compatible](./reference/openai.md) | `openAiCompatible()` and the other OpenAI exports |
262
266
  | `llm-large-files/anthropic` | [Claude](./reference/anthropic.md) | `anthropic()` and the other Anthropic exports |
263
- | `llm-large-files/node` | [Node HTTP handlers](./reference/node.md) | `createDocumentHandlers`: routes, requests, responses and statuses; `createIsolatedExtractors`, files read in child processes; `writeSseEvents` and `sseMessageOf`, events as Server-Sent Events |
267
+ | `llm-large-files/node` | [Node HTTP handlers](./reference/node.md) | `createDocumentHandlers`: routes, requests, responses and statuses, `prepareUpload` and `uploadSpool`; `createIsolatedExtractors`, files read in child processes; `fileOriginals`, the uploads your application keeps, read back by their ref; `writeSseEvents` and `sseMessageOf`, events as Server-Sent Events |
268
+ | `llm-large-files/testing` | [Testing](./reference/testing.md) | New in 0.9.0. `fakeModel`, a scripted model; `fakeFetch`, a `fetch` for the real adapters; test documents; `documentStoreChecks`, the checks of a store of your own |
264
269
 
265
270
  ## Internals and measurements
266
271
 
@@ -281,8 +286,16 @@ headings, each pointing to its new home.
281
286
  - [Publishing](./publishing.md): releasing a version to npm.
282
287
  - [Contributing](https://github.com/renanbazinin/llm-large-files/blob/main/CONTRIBUTING.md): how to work on the code and its tests.
283
288
 
284
- ## Changelog
289
+ ## Changelog and upgrading
285
290
 
286
291
  [CHANGELOG.md](../CHANGELOG.md) says what changed in each version. From 0.6.0 on, each version
287
292
  starts with what you must change when you upgrade, then what you can add, what works differently
288
293
  and what was fixed.
294
+
295
+ [Upgrading to 0.10](./upgrading-0.10.md) takes an application from 0.9.0 to 0.10.0: what no longer
296
+ compiles, the one prompt-cache miss, behavior to check, the worked example of the 0.9 guide carried
297
+ over, loops of your own, Vertex AI controls, operations on a shared volume and rolling deploys.
298
+
299
+ [Upgrading to 0.9](./upgrading-0.9.md) takes an application from 0.8.x to 0.9.0: what no longer
300
+ compiles, behavior to check, stores of your own, servers of two versions on one store, and a worked
301
+ example of a chatbot with a folder per user and chat on a shared volume.
@@ -9,17 +9,15 @@ adding the library to an app. Each step is short and links to the guide that exp
9
9
  npm install llm-large-files
10
10
  ```
11
11
 
12
- The library needs Node.js 20.19 or later. It is an ES module, and its TypeScript types come with
13
- it. From CommonJS code, `require("llm-large-files")` works on the Node versions that load ES
14
- modules with `require()` by default: 20.19 and later in Node 20, 22.12 and later, and 23 and later.
15
- On Node 21 and on 22.0 to 22.11, load it with `import("llm-large-files")`.
12
+ The library needs Node.js 22.12 or later (20.19 until 0.9.0). It is an ES module, and its
13
+ TypeScript types come with it. From CommonJS code, `require("llm-large-files")` works: Node 22.12
14
+ and later load ES modules with `require()` by default.
16
15
 
17
16
  Text, Markdown, logs, JSON and CSV need nothing more. Three optional packages add the rest:
18
17
 
19
18
  ```bash
20
19
  npm install jszip unpdf @cantoo/pdf-lib # Node 24 and later
21
20
  npm install jszip unpdf@1 @cantoo/pdf-lib # Node 22
22
- npm install jszip unpdf@1.7.0 @cantoo/pdf-lib # Node 20
23
21
  ```
24
22
 
25
23
  | Package | What it enables |
@@ -34,9 +32,9 @@ turn on `keepOriginals`: without it, every look at a page fails. The details are
34
32
  [PDFs](./guides/pdfs.md).
35
33
 
36
34
  On Node 24 and later, `npm install unpdf` installs unpdf 2, which asks for Node 24. On Node 22,
37
- install `unpdf@1`, and on Node 20, `unpdf@1.7.0`. An unpdf that cannot read PDFs on your version
38
- of Node is refused at the first PDF, with a message that says what to install, such as
39
- `The unpdf installed cannot read PDF files on Node 20 (…). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.`
35
+ install `unpdf@1`. An unpdf that would stop the server on your version of Node is refused at the
36
+ first PDF, with a message that says what to install:
37
+ `The unpdf installed would stop the whole server at the first PDF file on Node 22, so PDF files are not read. Install unpdf 1.6.1 or later, or run Node 24 or later.`
40
38
 
41
39
  The Vertex AI samples on this page also use Google's auth library, which is not a dependency of
42
40
  this package:
@@ -274,7 +272,9 @@ Keep the `id` with the chat session. Not on a Node HTTP server, or taking multip
274
272
 
275
273
  `getOwner` returns the signed-in user's ID, or `undefined` for an anonymous upload. An empty
276
274
  string, a string of spaces or `null` would be one owner shared by every caller without a user, so
277
- the upload is refused: `500` with `{ "error": "Upload failed (empty owner)." }`. Return the ID
275
+ the upload is refused: `500` with `{ "error": "Upload failed (empty owner)." }`. (With
276
+ `requireOwner: true`, `undefined` and `null` are answered `401` "Sign in first.", new in 0.9.0.)
277
+ Return the ID
278
278
  itself, not the user object (`{ "error": "Upload failed (owner is not a string)." }`). Both come
279
279
  before the body is read.
280
280
 
@@ -451,15 +451,20 @@ git clone https://github.com/renanbazinin/llm-large-files
451
451
  cd llm-large-files
452
452
  npm install
453
453
  npm run build
454
- GEMINI_API_KEY=... node examples/server.ts # then open http://localhost:3000
454
+ GEMINI_API_KEY=... node examples/server.ts # then open http://127.0.0.1:3000
455
455
  GEMINI_API_KEY=... node examples/ask-cli.ts ./big.log "What failed first, and when?"
456
456
  ```
457
457
 
458
458
  - `examples/server.ts` is a chat server in one file, on `node:http`: an upload route
459
459
  (`createDocumentHandlers`), answers streamed as Server-Sent Events, and a small web page. It
460
- stores uploads in `.data/large-files` and keeps PDFs, so the model can look at their pages.
461
- `GEMINI_MODEL` picks the model (default `gemini-3.8-flash`), and `GEMINI_EXPLORER_MODEL` adds an
462
- explorer model. Every upload is anonymous.
460
+ stores uploads in `.data/large-files` and keeps PDFs, so the model can look at their pages. It
461
+ reads PDF and Office files in child processes (`createIsolatedExtractors`). `GEMINI_MODEL` picks
462
+ the model (default `gemini-3.8-flash`), and `GEMINI_EXPLORER_MODEL` adds an explorer model.
463
+ - It is a demo, not for production as is. It listens on `127.0.0.1` only (`HOST` and `PORT` change
464
+ that). It has no sign-in: the page gives each browser a random owner in an `HttpOnly`,
465
+ `SameSite=Strict` cookie, so two browsers cannot read each other's files or chats, but whoever
466
+ has the cookie is that owner. Since 0.9.0; before, every upload was anonymous and the server
467
+ listened on every interface.
463
468
  - `examples/ask-cli.ts` asks one question about one file from the command line. Two more
464
469
  arguments are optional: the model, and an explorer model.
465
470
 
@@ -67,7 +67,7 @@ is tested against the request and response shapes of the Messages API documentat
67
67
  | `tokenScale` | 1.35 | How many of Claude's tokens one token of the library's estimate comes to. |
68
68
  | `body`, `analysisBody` | none | More fields for every chat request, and `(maxOutputTokens) => fields` for the part reads of a whole-file read: `thinking`, `output_config`. |
69
69
  | `firstByteTimeoutMs`, `idleTimeoutMs` | 600,000 and 300,000 | Waits on a chat reply that sends nothing. 0 waits without end. |
70
- | `timeoutMs` | 180,000 | Milliseconds one part read of a whole-file read may take. |
70
+ | `timeoutMs` | 180,000 | Milliseconds one part read of a whole-file read may take. 0 sets none (since 0.10.0). |
71
71
 
72
72
  The sections below explain each, and more: `stream` and `eagerInputStreaming` in
73
73
  [Streaming and waits](#streaming-and-waits), `cache` in [Prompt caching](#prompt-caching),
@@ -189,7 +189,10 @@ reading of the reply follow the options, not `body`.
189
189
  for such a connection to close, and took one that broke for a model that could not be reached,
190
190
  with the whole answer already shown.
191
191
  - **Part reads are not streamed.** Each may take `timeoutMs` (180 s); one that takes longer is
192
- stopped and tried once more.
192
+ stopped and tried once more. Since 0.10.0 it is an `AnthropicRequestError` of kind `"timeout"`
193
+ and status 0 ("Claude took longer than 180 s to answer."), as in the other adapters; before, the
194
+ error of the timer's abort, with no status. The tool tells the model "The model took too long to
195
+ answer."
193
196
 
194
197
  Streaming the answer on to a browser is in [web app](./web-app.md), and proxies that cut long
195
198
  streams in [deployment](./deployment.md).
@@ -296,10 +299,13 @@ the conversation they were written in, so an earlier turn that is rewritten make
296
299
  invalid. The loop therefore never rewrites a turn of a question in which a model that is
297
300
  append-only takes part: Claude alone, Claude answering, or Claude exploring. Three things change.
298
301
 
299
- **Old results are never replaced by stand-ins.** With other models, when the room in the request
300
- runs short, the loop replaces the results of older tool rounds with short stand-ins, and `steps`
301
- says "Older tool results were shortened to make room in the request". With Claude every result
302
- stays as it was. When the calls of a turn do not all fit, the last ones are answered "Not run:
302
+ **Old results are never replaced by stand-ins during a question.** With other models, when the
303
+ room in the request runs short, the loop replaces the results of older tool rounds with short
304
+ stand-ins, and `steps` says "Older tool results were shortened to make room in the request". With
305
+ Claude every result of the question stays as it was. The stored rounds of earlier questions are
306
+ the exception (new in 0.9.0): when they make the first request of a question larger than its
307
+ room, their results are replaced before that request is sent. They hold no thinking blocks, and
308
+ nothing of the question was sent yet. Before, such a question was refused and failed. When the calls of a turn do not all fit, the last ones are answered "Not run:
303
309
  there is no room left in this conversation for another tool result. Answer now, from what the
304
310
  tools returned so far.", and the next request is the answer. This holds for the whole question:
305
311
  with Claude answering and Gemini exploring, the explorer's rounds are not shortened either.
@@ -334,9 +340,10 @@ What this means for your application:
334
340
  - **Set `contextTokens`** to your model's window, and keep `maxTokens` no larger than you need. A
335
341
  right budget is what keeps Claude's requests inside its window.
336
342
  - **Keep the history in check between questions.** The library shortens no plain turn of the
337
- history, for any model, and with Claude it shortens no stored tool round either. A long history
338
- leaves less room for each new question: its documents become cards sooner, fewer results fit,
339
- and at last its first request is too large. Between two questions the history you pass is yours
343
+ history, for any model. With Claude it shortens the stored tool rounds only before the first
344
+ request, and only as far as the request needs (since 0.9.0). A long history leaves less room
345
+ for each new question: its documents become cards sooner, fewer results fit, the stored rounds
346
+ are sent as stand-ins, and at last its plain turns alone are too large. Between two questions the history you pass is yours
340
347
  to shorten: it holds no thinking blocks, and the rule above is about the turns of one question.
341
348
  Keeping the text of every turn and the `toolTurns` of the last few questions is a simple rule.
342
349
  The prompt cache misses once from the first turn you change. See
@@ -571,7 +578,7 @@ What the pair changes:
571
578
  Gemini's scale, Claude's by Claude's, so the estimate rises when either model counted more than
572
579
  its scale says. Before 0.6.0 every count was read by the largest scale, and a Gemini explorer's
573
580
  could not raise it.
574
- - **No result is shortened.** Claude is append-only, so the rule
581
+ - **No result of the question is shortened.** Claude is append-only, so the rule
575
582
  [above](#a-conversation-that-may-only-grow) holds for the explorer's rounds too.
576
583
  - **Claude gets the calls and what they returned**, in its own form: an assistant turn of
577
584
  `tool_use` blocks and a user turn of `tool_result` blocks. A call that came without an ID is
@@ -32,8 +32,8 @@ The rules:
32
32
  - **A `native` part goes unchanged to every model of the question**: a Gemini part to `gemini()`, a
33
33
  Chat Completions content part to `openAiCompatible()`, a Messages API block to `anthropic()`.
34
34
  With an [explorer model](./explorer-model.md) of another provider, both models get it, so both
35
- must read it. A native part that also has `text` is sized by that text; one without is sized by
36
- the length of its JSON, as media.
35
+ must read it. A native part that also has `text` is counted in tokens by that text, and in bytes
36
+ by the larger of that text and its JSON; one without is sized by the length of its JSON, as media.
37
37
 
38
38
  Annotate the array as `ChatMessage[]`. Without the annotation TypeScript widens `role` to
39
39
  `string`, and the array is not accepted as `messages`.
@@ -66,12 +66,11 @@ const messages: ChatMessage[] = [
66
66
  const second = await askWithFiles({ files, model, documentIds, messages });
67
67
  ```
68
68
 
69
- `askGemini` takes the conversation in one of two options. `messages` takes plain turns and stored
70
- tool rounds (`Array<ChatTurn | ToolTurn>`), and no native parts. `contents` takes Gemini
71
- `contents`, native parts included, and converts them with `fromGeminiContents`
72
- ([below](#gemini-contents)). When both are given, `contents` is used. For native parts and stored
73
- tool rounds in one history, call `askWithFiles` with `gemini(endpoint)`, as above; an explorer
74
- model is then passed as `explorer` ([Explorer model](./explorer-model.md)).
69
+ `askGemini` takes the conversation in one of two options. `messages` takes what `askWithFiles`
70
+ takes (`ChatMessage[]`): plain turns, stored tool rounds and, since 0.9.0, turns with native parts,
71
+ such as the chart's turn above. Before 0.9.0 it took only `Array<ChatTurn | ToolTurn>`. `contents` takes
72
+ Gemini `contents`, native parts included, and converts them with `fromGeminiContents`
73
+ ([below](#gemini-contents)). When both are given, `contents` is used.
75
74
 
76
75
  Every field of these types is in the reference: [`askWithFiles(options)`](../reference/ask.md#askwithfilesoptions)
77
76
  and the rest of [ask.md](../reference/ask.md).
@@ -103,12 +102,18 @@ tool calls of one model turn, each with what its tool returned:
103
102
  `tool_turns_left`, the tool turns the question had left then. A stand-in does not.
104
103
  - **`tool_turns_left` is stored, and not sent again.** When you pass the rounds back in a later
105
104
  question, the results go to the model without it: its count was of the turns their own question
106
- had left, and a model could take a 0 there for its own. So the first request of a follow-up
107
- differs from the requests of the question before it, from that question's first tool round on.
108
- The provider's prompt cache misses from there, once in each follow-up question, in its first
109
- request; the rounds of older questions were already sent without the count and still match, and
105
+ had left, and a model could take a 0 there for its own.
106
+ - **So the first request of a follow-up differs from the requests of the question before it**,
107
+ from that question's first tool round on, for two reasons. The results are sent without
108
+ `tool_turns_left`. And the model turns of the round are sent as their calls alone: within its own
109
+ question a round went back with the model's own form of its turn (Gemini's thought signatures,
110
+ Claude's thinking blocks), and a stored round has none ([below](#what-toolturns-holds)). Either
111
+ one alone makes the provider's prompt cache miss from there, once in each follow-up question, in
112
+ its first request. The rounds of older questions were already sent that way and still match, and
110
113
  the documents and cards before the rounds are still read from the cache
111
- ([Costs and limits](./costs-and-limits.md#prompt-caching)).
114
+ ([Costs and limits](./costs-and-limits.md#prompt-caching)). Before 0.9.0 these pages named
115
+ `tool_turns_left` alone; keeping the count in the results would not save the miss for a model
116
+ that thinks. Keeping the raw turns is planned for a later version.
112
117
  - Calls that were not run are there too, with an `error`: for example refused for lack of room,
113
118
  past `limits.callsPerTurn`, or whose arguments could not be read. So are pointers to results already
114
119
  shown ([Repeated calls](#repeated-calls-in-a-follow-up)).
@@ -118,6 +123,7 @@ tool calls of one model turn, each with what its tool returned:
118
123
  them." }`.
119
124
  - **No provider's own form.** A stored round has no thought signatures, thinking blocks or other
120
125
  raw parts of the model turn. Any adapter can be given it, and builds the turn from the calls.
126
+ That is one of the two reasons the prompt cache misses once in a follow-up (above).
121
127
  - Only the rounds of this question. The stored rounds you passed in `messages` are not repeated.
122
128
  - With an explorer model they are the explorer's rounds. Its words are not kept.
123
129
  - They are there when `answered` is false, and in `partialResultOf(error)` when the question failed.
@@ -261,7 +267,11 @@ its own in some ways, and not in others.
261
267
  whole, which the model reaches only through the tools.
262
268
  - **It shortens old tool results.** When the results of a new turn do not fit, the results of all
263
269
  but the last three tool rounds are replaced by short stand-ins, then all but the last two, then
264
- all but the last one. Stored rounds of earlier questions are the oldest, so they go first. A
270
+ all but the last one. Stored rounds of earlier questions are the oldest, so they go first.
271
+ Since 0.9.0 this is done before the first request too, when the stored rounds make it larger
272
+ than its room in tokens (the loop's estimate, which the recovery from a refused request uses
273
+ too; a request is not shortened for its bytes alone): the first request goes out shortened,
274
+ instead of being refused by the provider and sent again. A
265
275
  stand-in keeps the document and the lines or pages that were shown, and tells the model to read
266
276
  them again if it needs them:
267
277
 
@@ -270,7 +280,9 @@ its own in some ways, and not in others.
270
280
  ```
271
281
 
272
282
  Errors and results under 700 characters are left as they are, except a `view_pages` result
273
- that showed pages: it is always replaced, and its pages go with it. A whole-file read keeps the
283
+ that showed pages: it is always replaced, and its pages go with it. Since 0.9.0 a result that
284
+ its stand-in would not make smaller is left as it is too, such as a search counted by group with
285
+ a few short groups. A whole-file read keeps the
274
286
  first 6,000 characters of its answer. `steps` then holds "Older tool results were shortened to
275
287
  make room in the request".
276
288
  - **It stops running tools when nothing fits.** A call that cannot get 1,500 characters of room is
@@ -285,10 +297,12 @@ its own in some ways, and not in others.
285
297
  What it does not do:
286
298
 
287
299
  - **It never shortens a text turn**, a question or an answer, and never touches native parts.
288
- - **It never shortens anything for an append-only model.** When a model of the question declares
289
- `appendOnly` (Claude does: [Claude](./anthropic.md)), no turn is rewritten during the question, and
290
- old results are not replaced by stand-ins. The check of stored pointers at the start of a
291
- question ([below](#repeated-calls-in-a-follow-up)) still runs.
300
+ - **It never shortens anything of the question for an append-only model.** When a model of the
301
+ question declares `appendOnly` (Claude does: [Claude](./anthropic.md)), no turn is rewritten
302
+ during the question, and its results are not replaced by stand-ins. The check of stored pointers
303
+ at the start of a question ([below](#repeated-calls-in-a-follow-up)) still runs, and since 0.9.0
304
+ so does the shortening of stored rounds before the first request: they hold no thinking blocks,
305
+ and nothing of the question was sent yet. Before, such a question failed on Claude.
292
306
  - **It does not change your stored rounds.** Stand-ins exist in the requests of one question. The
293
307
  `toolTurns` it returns are the new rounds as the model last had them.
294
308
 
@@ -435,17 +449,36 @@ export async function next(files: LargeFiles, endpoint: GeminiEndpoint, document
435
449
  - `geminiToolTurns` gives, for each round, a `model` turn of `functionCall` parts and a `user` turn
436
450
  of `functionResponse` parts. A call's `id` is in both when it has one. Each result is given
437
451
  without its `tool_turns_left`, as the loop sends the rounds of an earlier question. `contents`
438
- that 0.5.0 converted keep it, and are sent as they are.
439
- - `fromGeminiContents` makes a `"user"` turn a user turn and a `"model"` turn an assistant turn. A
440
- text part is text. A text part with more fields (a `thoughtSignature`) is kept whole as a native
441
- part, sized by its text. Every other part is a native part, as it is: an image, an inline PDF,
442
- and the `functionCall` and `functionResponse` parts of earlier questions.
443
-
444
- So stored rounds in `contents` reach Gemini unchanged: the request is the same as with `messages`
445
- and `ToolTurn`s. The loop does not see them as tool rounds, though. It cannot shorten them to make
446
- room, does not point a repeated call to them, and sizes them only roughly, as media. No helper
447
- turns Gemini function calls back into `ToolTurn`s. Where you can, keep `toolTurns` as the JSON they
448
- are, and pass them in `messages`.
452
+ that 0.5.0 converted keep it; from 0.9.0 their rounds are sent without it (below).
453
+ - `fromGeminiContents` makes a `"user"` turn a user turn and a `"model"` turn an assistant turn,
454
+ and the rounds that `geminiToolTurns` wrote stored rounds again (below). A text part is text. A
455
+ text part with more fields (a `thoughtSignature`) is kept whole as a native part: its tokens are
456
+ counted from its text, and its bytes from the whole part. Every other part is a native part, as
457
+ it is: an image, an inline PDF, and the `functionCall` and `functionResponse` parts of your own
458
+ functions.
459
+
460
+ Since 0.9.0, `contents` and `messages` with `ToolTurn`s behave alike. `fromGeminiContents` turns
461
+ the rounds `geminiToolTurns` wrote back into stored rounds: a `model` turn of `functionCall` parts
462
+ of the library's tools, followed by the `user` turn of their `functionResponse` parts. For the
463
+ rounds that `geminiToolTurns` wrote, the request is the same, byte for byte, as before. But now
464
+ the loop can shorten them to make room, point a
465
+ repeated call to them, and size them as it sizes `toolTurns`. Before, it saw them as plain parts:
466
+ a repeated search was run again, nothing could be shortened, and they were sized as media, about
467
+ 15,000 tokens short for a round of two calls.
468
+
469
+ - A turn of your own functions, or one with a thought signature or a file in a response, stays as
470
+ it is. Its tokens are counted from the JSON of its calls and responses, and its bytes from the
471
+ whole parts, a thought signature included.
472
+ - A round at the end of `contents`, with no turn after it, stays as it is too. Its responses are
473
+ the turn the model answers, as when your application ran the tools in a loop of its own and
474
+ hands the conversation over.
475
+ - `fromGeminiContents(contents, { rounds: false })` keeps every turn as its parts, as 0.8 did.
476
+ With `askGemini`, pass it as `messages`.
477
+ - The stored rounds come back without `tool_turns_left`, as stored `ToolTurn`s are sent. The
478
+ rounds that `geminiToolTurns` wrote never had it. Rounds that 0.5.0 converted have it in their
479
+ responses: from 0.9.0 they are lifted too, and sent without it, and a call without `args` is
480
+ sent with `args: {}`. Such a conversation misses the prompt cache once, in its first request
481
+ after the upgrade, from that round on.
449
482
 
450
483
  ### Chat Completions messages
451
484
 
@@ -581,11 +614,20 @@ the explorer's calls and results, built in its own form ([Explorer model](./expl
581
614
 
582
615
  - **Pass the same `owner` with every question.** A document ingested with another owner is treated
583
616
  as missing. The owner is a string that is not empty: `ingest` refuses `""`, which
584
- `user?.id ?? ""` gives a caller who is not signed in. How to choose the owner (a user, or a user
585
- and a session) is in [Storage](./storage.md#how-ownership-works).
617
+ `user?.id ?? ""` gives a caller who is not signed in. How to choose the owner is in
618
+ [Storage](./storage.md#how-ownership-works).
619
+ - **Pass the chat as `scope`**, new in 0.9.0: `scope: [userId, sessionId]` at ingest and with every
620
+ question. A document of another chat is then treated as missing, even one of the same user
621
+ ([Scopes](./storage.md#scopes)).
622
+ - **Give the documents IDs of your own** (`IngestInput.id`, new in 0.9.0), such as the ID of the
623
+ upload. The stored rounds (`toolTurns`) name the documents by ID. A file ingested again under the
624
+ same ID (from the upload you kept, once it expired) is found by those rounds and by the session
625
+ record as it is: nothing to rewrite. With the IDs the library makes, each ingest gives a new ID,
626
+ and the rounds keep naming the old one.
586
627
  - **Keep the documents with the conversation, not with one message.** Pass all of them in
587
628
  `documentIds` on every question. They are planned again each time.
588
- - **A document that is gone stops the question before any model request.** One that expired, was
629
+ - **A document that is gone is settled before any model request**, by `onMissingDocuments`
630
+ ([below](#documents-that-are-gone)). By default the question stops: one that expired, was
589
631
  deleted, or belongs to another owner raises `DocumentsNotFoundError`, with the IDs in `.ids` and
590
632
  the message "A document is no longer available: doc_…. Upload it again." `partialResultOf` gives
591
633
  undefined for it: nothing was asked.
@@ -598,26 +640,49 @@ the explorer's calls and results, built in its own form ([Explorer model](./expl
598
640
  document: its expiry (`ttlMs` of `createLargeFiles`) and `files.delete`. Your rules for keeping and
599
641
  deleting data must cover them ([Security](../security.md), [Storage](./storage.md)).
600
642
 
601
- With the session sample above, documents that are gone can be taken off the session, and the user
602
- asked for them again:
643
+ ### Documents that are gone
644
+
645
+ A chat often lives longer than its documents: they expire after `ttlMs` (72 hours by default), or
646
+ are deleted. Before 0.9.0 the next question then failed whole with `DocumentsNotFoundError`, and
647
+ the application caught it, took the IDs off the chat and asked again. Since 0.9.0
648
+ `onMissingDocuments` does it in the question ([missing documents](../reference/ask.md#missing-documents)):
649
+
650
+ - `"drop"` answers without them. The model is told, in one line of the system instruction, how many
651
+ files are no longer available, so it can say so when the question needs them. `result.missing`
652
+ lists their IDs, and a `documents_missing` notice names them, for the page.
653
+ - A function can ingest them again, from the uploads you kept, under the same IDs, and return
654
+ `{ retry: true }`; or under new IDs, and return `{ replace: { [oldId]: newId } }`. The question is
655
+ then planned again, once, with them.
656
+
657
+ With the session sample above, the files that are gone are taken off the chat, and the user is told:
603
658
 
604
659
  ```ts
605
- import { DocumentsNotFoundError } from "llm-large-files";
660
+ import { askGemini } from "llm-large-files/gemini";
606
661
 
607
- // `ask` and `sessions` are those of the session sample above.
608
- /** Asks the question, or says which files must be attached again. */
609
- export async function askOrExplain(sessionId: string, userId: string, question: string, onText: (delta: string) => void, signal: AbortSignal): Promise<string | undefined> {
610
- try {
611
- await ask(sessionId, userId, question, onText, signal);
612
- return undefined;
613
- } catch (error) {
614
- if (!(error instanceof DocumentsNotFoundError)) throw error;
615
- await sessions.updateOne({ _id: sessionId, userId }, { $pull: { documentIds: { $in: error.ids } } });
616
- return error.ids.length === 1 ? "A file of this chat is no longer available. Please attach it again." : `${error.ids.length} files of this chat are no longer available. Please attach them again.`;
617
- }
662
+ // `files`, `endpoint`, `sessions`, `turns` and `historyOf` are those of the session sample above.
663
+ /** Asks the question without the files that are gone. Returns what to tell the user about them. */
664
+ export async function askWithoutGone(sessionId: string, userId: string, question: string, onText: (delta: string) => void, signal: AbortSignal): Promise<string | undefined> {
665
+ const session = await sessions.findOne({ _id: sessionId, userId });
666
+ if (!session) throw new Error("No such chat.");
667
+ const earlier = await turns.find({ sessionId }).sort({ index: 1 }).toArray();
668
+ const result = await askGemini({
669
+ files, endpoint, owner: userId, documentIds: session.documentIds, messages: historyOf(earlier, question),
670
+ onMissingDocuments: "drop", onText, signal,
671
+ });
672
+ if (!result.missing) return undefined;
673
+ await sessions.updateOne({ _id: sessionId, userId }, { $pull: { documentIds: { $in: result.missing } } });
674
+ return result.missing.length === 1 ? "A file of this chat is no longer available. Please attach it again." : `${result.missing.length} files of this chat are no longer available. Please attach them again.`;
618
675
  }
619
676
  ```
620
677
 
678
+ - Keep its turn as the sample above does: `result.toolTurns` and the answer.
679
+ - With your own IDs ([above](#owners-and-documents-across-turns)), the uploads you keep can bring
680
+ a file back instead: the sample under [missing documents](../reference/ask.md#missing-documents)
681
+ ingests each one again from its upload and returns `{ retry: true }`.
682
+ - A tool call that finds a document gone during the question (deleted while the question ran)
683
+ answers the model that it is no longer available, and the question gets a `document_gone`
684
+ notice ([events](../reference/events.md#noticecode-and-noticedisplay)).
685
+
621
686
  ## Related pages
622
687
 
623
688
  - [Web app](./web-app.md): uploads, streaming the answer, cancelling.