llm-large-files 0.5.0 → 0.8.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 (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,728 @@
1
+ # Costs and limits
2
+
3
+ This guide is for you if you need to bound what one question may spend, or to count what it did
4
+ spend. It covers the limits of a question, the budget that decides what goes into each request, the
5
+ usage a question reports, cost per user or per chat session, and the features that cost most. Every
6
+ field and default is in the reference: [`AskLimits`](../reference/ask.md#asklimits),
7
+ [`AskResult`](../reference/ask.md#askresult) and [`Budget`](../reference/library.md#budget).
8
+
9
+ ## Where the tokens go
10
+
11
+ One question is a chain of model requests:
12
+
13
+ - **Chat requests.** Each one carries your system instruction and the tool guide, the conversation,
14
+ the documents sent whole (or a card for each document that is searched), the tool declarations,
15
+ and every tool result of the question so far. So each request of the tool loop is larger than the
16
+ one before, and the documents sent whole are read again by every request.
17
+ - **Part reads.** A whole-file read (`analyze_whole_document`) sends the file to the model in parts,
18
+ one request each, then writes an answer from their notes. When the notes together are larger
19
+ than one part, it merges them first.
20
+ - **Pages.** A page that `view_pages` showed stays in every later request of the question.
21
+
22
+ The last request writes the answer. A question about documents that are sent whole, with no pages to
23
+ look at, is a single request. [How it works](../how-it-works.md) has the details.
24
+
25
+ ## The limits of a question
26
+
27
+ `limits` of `askWithFiles` and `askGemini` bounds one question, whatever the model decides to do:
28
+
29
+ ```ts
30
+ import { GoogleAuth } from "google-auth-library";
31
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
32
+ import { askGemini, vertexAi } from "llm-large-files/gemini";
33
+
34
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
35
+ const endpoint = vertexAi({
36
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
37
+ location: process.env.GOOGLE_CLOUD_LOCATION ?? "global",
38
+ model: "gemini-3.8-flash",
39
+ explorerModel: process.env.GEMINI_EXPLORER_MODEL, // optional: a cheaper model searches and reads
40
+ accessToken: async () => (await auth.getAccessToken())!,
41
+ });
42
+ const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
43
+
44
+ export async function ask(userId: string, documentIds: string[], question: string) {
45
+ const result = await askGemini({
46
+ files,
47
+ endpoint,
48
+ owner: userId,
49
+ documentIds,
50
+ messages: [{ role: "user", text: question }],
51
+ limits: {
52
+ toolTurns: 8, // at most 8 chat requests, the answer included, plus one when the answer comes back without text
53
+ callsPerTurn: 6, // at most 6 tool calls run in one turn
54
+ wholeDocumentReads: 1, // each document is read whole once at most (the default)
55
+ inputTokens: 1_500_000, // no more tools once the question has used this many input tokens
56
+ requests: 30, // chat requests and part reads together
57
+ },
58
+ });
59
+ console.log(result.turns, result.usage);
60
+ return result;
61
+ }
62
+ ```
63
+
64
+ | Limit | Default | What it counts | When it is reached |
65
+ |---|---|---|---|
66
+ | `toolTurns` | 12 | Chat requests of the question: the answer and the second tries after an empty or broken turn included. The second try of the answer itself, when it came back without text, can be one request past it. | The last request must be answered in text (`toolChoice: "none"`; Gemini gets no tools declared, the other adapters keep them listed). |
67
+ | `callsPerTurn` | 8 | Tool calls of one model turn that are run. | Each call past it is answered "Not run: one turn runs at most 8 tool calls. Send this call again if you still need it." |
68
+ | `wholeDocumentReads` | 1 | Whole-file reads of each document. | A read past it is answered with an error that tells the model to use the answer it already has. 0 refuses every read. |
69
+ | `inputTokens` | none | Input tokens of the question: every chat request and part read, of every model. | No more tools run: the next request is the answer. A whole-file read that would pass it is refused before it starts. |
70
+ | `requests` | none | Answered requests of the question: chat requests and part reads together. | Once one request is left, no more tools run, and that request is the answer. A whole-file read that would pass it is refused before it starts. |
71
+
72
+ **No limit throws.** A question that reaches a limit ends with a request for the answer, written
73
+ from what the tools returned so far. That request usually ends with `FINAL_ANSWER_REQUEST`: "Stop
74
+ using tools now. Answer my question using only what the tools returned above, with line citations.
75
+ Say plainly what you could not find. Answer in the language of my question." When no tool ran (for
76
+ example with `toolTurns: 1` or `requests: 1`), it ends with `FINAL_ANSWER_WITHOUT_TOOLS` instead.
77
+ When pages were the only thing to look at, it ends with `FINAL_ANSWER_AFTER_PAGES`. `answered` is
78
+ true when the reply has text and was not refused.
79
+
80
+ - **The answer is asked for once more when it comes back without text**: empty, or with a tool call
81
+ the model was told not to make. The note "Your last reply had no text. No tool can be called in
82
+ this reply: write the answer now, in text, from what is above." goes at the end of that one
83
+ request. It is one of the two second tries a question may make, and it can be one request past
84
+ `toolTurns`. It is not made after a refusal, a filter or a reply cut off at the output limit with
85
+ nothing in it, nor once `requests` or `inputTokens` is reached: those two are never passed by
86
+ it. With `toolTurns: 8`, a question makes at most 9 answered chat requests; to cap them exactly,
87
+ set `requests`.
88
+ - Each tool result carries `tool_turns_left`, so the model can see its turns run out and stop
89
+ searching in time. The results of an earlier question, passed back in `messages`, are sent
90
+ without it ([Conversations](./conversations.md#what-toolturns-holds)).
91
+ - A model that answers in text before a limit is reached ends the question there.
92
+ - The result does not say that a limit ended the question, and `steps` has no line for it. When
93
+ `result.turns` reaches `toolTurns`, the model was most likely still calling tools when its turns
94
+ ran out. `result.usage` shows how close the question came to `inputTokens` and `requests`.
95
+ - With an explorer model, the limits count the work of both models together. The answer is always
96
+ a request of its own, so the explorer has at most `toolTurns − 1` requests
97
+ ([explorer model](./explorer-model.md)).
98
+ - `maxToolTurns` and `maxToolCallsPerTurn` of `askGemini` are `toolTurns` and `callsPerTurn` under
99
+ their names from before 0.5.0. When both are given, `limits` wins.
100
+
101
+ ### `inputTokens` and `requests` are checked between turns
102
+
103
+ - **They are checked before each tool turn**, against what the question has used so far. The
104
+ request that crosses `inputTokens` has already been sent: its tool calls run, and then the answer
105
+ is asked for. So a question can pass `inputTokens` by about two requests: the one that crossed
106
+ it, and the answer, which reads everything the tools returned. Set the ceiling that far below
107
+ what must not be passed.
108
+ - **`requests` keeps one request for the answer**, so the answer stays within it.
109
+ - **A whole-file read is reckoned before it starts.** In input tokens, it is the size of the file
110
+ in the tokens of the model that reads it. In requests, it is its parts, one merge of their notes,
111
+ its answer, and the answer of the question. A read that does not fit what is left is not run, and
112
+ costs nothing. The model gets the reason, for example: "Not run: reading all of app.log takes
113
+ about 2,400,000 input tokens, and 900,000 are left of the 1,500,000 this question may use. Use
114
+ search_document and read_document." Reads let through in the same turn share what is left. A read
115
+ whose notes need more than one merge can pass `requests` by those merges.
116
+ - **A request that failed and was sent again counts once**, as it does in `usage`.
117
+
118
+ ### Tools you can leave out
119
+
120
+ ```ts
121
+ import { askGemini } from "llm-large-files/gemini";
122
+
123
+ // files and endpoint as in the first sample. documentIds and question are yours.
124
+ const result = await askGemini({
125
+ files,
126
+ endpoint,
127
+ documentIds,
128
+ messages: [{ role: "user", text: question }],
129
+ wholeDocumentAnalysis: false, // no analyze_whole_document: no part reads
130
+ viewPages: false, // no view_pages: no pages in the requests
131
+ });
132
+ ```
133
+
134
+ - **`wholeDocumentAnalysis: false`** leaves `analyze_whole_document` out of the tools of every
135
+ request: the question makes no part reads. A model that explores without `generateText` (the
136
+ explorer when there is one, otherwise `model`) has no whole-file reads either. In both cases the
137
+ tool guide and the cards do not mention whole-file reads.
138
+ - **`limits.wholeDocumentReads: 0`** keeps the tool and refuses every call of it: "Whole-file reads
139
+ are turned off for this question. Use search_document and read_document on app.log." Each refused
140
+ call still takes a place in a turn. Prefer `wholeDocumentAnalysis: false`.
141
+ - **`viewPages: false`** leaves `view_pages` out, and the tool guide does not mention it.
142
+
143
+ Neither changes which documents are sent whole: that is the budget's work.
144
+
145
+ ## The budget
146
+
147
+ The budget describes your model connection: how large one request may be, and how it is shared
148
+ between documents, tool results, pages and the answer. The library plans every request with it.
149
+
150
+ ### What each field decides
151
+
152
+ | Field | Default | What it decides |
153
+ |---|---|---|
154
+ | `contextTokens` | 1,000,000 | The window a question is planned for. |
155
+ | `maxRequestBytes` | 10,000,000 | The largest request body. It is checked apart from tokens: non-English text and JSON escaping make bytes run ahead of tokens. |
156
+ | `inlineTokens` | half the window, 200,000 at most | The most document text sent whole in one request. Lower it to send fewer documents whole; raise it to rely on the long context more. |
157
+ | `reservedTokens` | a quarter of the window, 64,000 at most | Kept free of documents: for the answer, tool results and a growing history. Text tool results may fill the window up to `contextTokens − reservedTokens / 2`. Pages may take up to half of it. |
158
+ | `mapChunkTokens` | half the window, 100,000 at most | The size of one part of a whole-file read. |
159
+ | `maxMapChunks` | 30 | The most parts of a whole-file read. A file that needs more is not read whole. |
160
+ | `toolResultCharacters` | 12% of the window, from 1,000 to 24,000 | The most characters of one tool result. The answer of a whole-file read may have 40,000, or this many when it is more. |
161
+
162
+ The defaults fit a model with a window of 1M tokens behind a request limit of 10 MB. For a model
163
+ with a smaller window, set `contextTokens`: the fields you leave out follow it.
164
+
165
+ | `contextTokens` | `inlineTokens` | `reservedTokens` | `mapChunkTokens` | `toolResultCharacters` |
166
+ |---|---|---|---|---|
167
+ | 1,000,000 | 200,000 | 64,000 | 100,000 | 24,000 |
168
+ | 200,000 | 100,000 | 50,000 | 100,000 | 24,000 |
169
+ | 128,000 | 64,000 | 32,000 | 64,000 | 15,360 |
170
+ | 32,768 | 16,384 | 8,192 | 16,384 | 3,932 |
171
+
172
+ `maxRequestBytes` and `maxMapChunks` do not follow the window.
173
+
174
+ ```ts
175
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
176
+
177
+ const files = createLargeFiles({
178
+ store: new FileDocumentStore("./data/large-files"),
179
+ budget: { contextTokens: 128_000, maxRequestBytes: 4_000_000 },
180
+ });
181
+ console.log(files.budget);
182
+ // { contextTokens: 128000, maxRequestBytes: 4000000, inlineTokens: 64000, reservedTokens: 32000,
183
+ // mapChunkTokens: 64000, maxMapChunks: 30, toolResultCharacters: 15360 }
184
+ ```
185
+
186
+ - **A field you set stays as you set it**, unless a model's window is smaller than the budget's
187
+ ([below](#one-library-several-models)). Then a value too large for that window is lowered:
188
+ `inlineTokens` to the window, `reservedTokens` and `mapChunkTokens` to half of it,
189
+ `toolResultCharacters` to the window (1,000 at least). `maxMapChunks` is never lowered.
190
+ - **Values that cannot work are an error.** A field that is not a number above 0 throws
191
+ "budget.inlineTokens must be a number above 0, and is 0." A `reservedTokens` or `mapChunkTokens`
192
+ at or above `contextTokens` throws, for example, "budget.reservedTokens (200,000) must be smaller
193
+ than budget.contextTokens (128,000): nothing would be left for the conversation."
194
+ `createLargeFiles` throws for the library's budget. `askWithFiles` and `askGemini` throw for the
195
+ `budget` of a question, before any request.
196
+ - **`budget` of `askWithFiles` and `askGemini`** changes fields for one question, such as
197
+ `budget: { inlineTokens: 20_000 }`. The other fields stay the library's.
198
+
199
+ `resolveBudget(partial, limits)` gives the whole budget for any set of fields.
200
+ `files.budgetFor(overrides, limits)` gives the library's budget with `overrides` in place of its
201
+ fields. Both fit the budget to `limits` ([`ModelLimits`](../reference/library.md#modellimits): a
202
+ model's `contextTokens` and `maxRequestBytes`) when those are smaller:
203
+
204
+ ```ts
205
+ import { resolveBudget } from "llm-large-files";
206
+
207
+ resolveBudget({ contextTokens: 200_000 });
208
+ // inlineTokens 100,000 · reservedTokens 50,000 · mapChunkTokens 100,000 · toolResultCharacters 24,000
209
+
210
+ // A value you set that is too large for a model's smaller window is lowered to fit it.
211
+ resolveBudget({ inlineTokens: 300_000 }, { contextTokens: 128_000 });
212
+ // contextTokens 128,000 · inlineTokens 128,000 · reservedTokens 32,000 · mapChunkTokens 64,000
213
+
214
+ // files as in the sample above: the library's budget with fewer parts for a whole-file read.
215
+ files.budgetFor({ maxMapChunks: 10 });
216
+ ```
217
+
218
+ ### Whole or searched
219
+
220
+ For each question the budget decides which documents go into the prompt whole, and which the model
221
+ reads through the tools. The library takes the size of everything else in the request (your system
222
+ instruction, the conversation and its stored tool rounds, and a margin of 2,000 tokens and 8,000
223
+ bytes), then fills the room that is left, smallest document first:
224
+
225
+ - token room: `min(inlineTokens, contextTokens − reservedTokens − the rest)`
226
+ - byte room: `maxRequestBytes − 256 KB − the rest`
227
+
228
+ A document goes whole when it fits both, after the smaller ones. The others get a card and the
229
+ tools. With the default budget and a short conversation, a log of 150,000 tokens goes whole. Add a
230
+ second log of 80,000 tokens, and the 80,000 go whole while the 150,000 are searched: the two
231
+ together are more than 200,000.
232
+
233
+ The sizes are the library's estimate of tokens (`estimatedTokens` of each document) and the text's
234
+ size in JSON. As the conversation grows, the room for documents shrinks, so a document that went
235
+ whole in the first question of a chat can be searched in a later one. `result.plan` says what
236
+ happened:
237
+
238
+ ```ts
239
+ // result: what askWithFiles or askGemini returned.
240
+ console.log("whole:", result.plan.inline.map((meta) => meta.name), result.plan.inlineTokens);
241
+ console.log("searched:", result.plan.searchable.map((meta) => meta.name));
242
+ ```
243
+
244
+ ### One library, several models
245
+
246
+ The budget of a question is the library's, with the question's `budget` in place of its fields,
247
+ made to fit the models of the question. An adapter says what its model takes in its
248
+ `capabilities` ([`ModelCapabilities`](../reference/ask.md#modelcapabilities)):
249
+
250
+ 1. **The window** is the smallest of the budget's `contextTokens` and the `contextTokens` of each
251
+ model. The same goes for `maxRequestBytes`.
252
+ 2. **The largest `tokenScale`** of the models divides it. The budget is counted in the library's
253
+ estimate of tokens, which is fitted to Gemini's count. A model whose tokenizer counts more tokens
254
+ for the same text has, in those terms, a smaller window.
255
+ 3. **The largest `outputTokens`**, divided the same way, is kept free. A model that counts its reply
256
+ against the window (Claude's `max_tokens`) leaves that much less for the prompt. At least a
257
+ quarter of the window is left.
258
+ 4. **The other fields** follow the window that results: those the library left out are worked out
259
+ from it, and those it set are lowered when they are too large for it.
260
+
261
+ What the adapters declare unless you set it:
262
+
263
+ | Adapter | `contextTokens` | `maxRequestBytes` | `tokenScale` | `outputTokens` | `pageTokens` |
264
+ |---|---|---|---|---|---|
265
+ | `gemini()` | only when set | only when set | 1 | none | 530 |
266
+ | `openAiCompatible()` | only when set | only when set | 1, or the option | none | 1,000 (pages need `pdfInput`) |
267
+ | `anthropic()` | only when set | 32,000,000 | 1.35, or the option | `maxTokens`: 64,000 | 3,500 |
268
+
269
+ A model that declares no window gets the library's: 1,000,000 tokens unless you set another. So
270
+ declare the window of every model whose window is smaller.
271
+
272
+ **With `askWithFiles`**, give each adapter its `contextTokens` (and `maxRequestBytes`), and every
273
+ question is planned for the smallest. Here a model on your own server explores for Gemini on
274
+ Vertex AI:
275
+
276
+ ```ts
277
+ import { GoogleAuth } from "google-auth-library";
278
+ import { askWithFiles, createLargeFiles, FileDocumentStore } from "llm-large-files";
279
+ import { gemini, vertexAi } from "llm-large-files/gemini";
280
+ import { openAiCompatible } from "llm-large-files/openai";
281
+
282
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
283
+ const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
284
+
285
+ // Writes the answers. Its window: 1,048,576 tokens.
286
+ const flash = gemini(vertexAi({
287
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
288
+ model: "gemini-3.8-flash",
289
+ accessToken: async () => (await auth.getAccessToken())!,
290
+ }), { contextTokens: 1_048_576 });
291
+
292
+ // Searches and reads. Its window: 131,072 tokens, and a tokenizer that counts a fifth more.
293
+ const local = openAiCompatible({
294
+ baseUrl: process.env.LOCAL_LLM_URL!,
295
+ model: process.env.LOCAL_LLM_MODEL!,
296
+ contextTokens: 131_072,
297
+ tokenScale: 1.2,
298
+ });
299
+
300
+ export async function ask(documentIds: string[], question: string) {
301
+ const result = await askWithFiles({ files, model: flash, explorer: local, documentIds, messages: [{ role: "user", text: question }] });
302
+ console.log(result.budget.contextTokens); // 109226: the library's 1,000,000, then 131,072, then / 1.2
303
+ return result;
304
+ }
305
+ ```
306
+
307
+ **With `askGemini`**, which makes its models without these numbers, put the window in the
308
+ library's `budget`, or in the `budget` of a question. With an explorer, use the smaller of the two
309
+ windows. [Vertex AI and Gemini](./vertex-and-gemini.md) has the setup.
310
+
311
+ `result.budget` is the budget a question ran with. `files.budgetFor(undefined, { contextTokens })`
312
+ gives the same in advance for a model that declares only a window. With a `tokenScale` or
313
+ `outputTokens`, only `result.budget` has it.
314
+
315
+ A window left too large is often recovered. The first request the provider refuses as too large
316
+ teaches the loop the window it names. Older tool results are shortened, or, when no tool has run
317
+ yet, the documents are planned again ([errors and reliability](./errors-and-reliability.md)). With
318
+ Claude, whose conversation may only grow, only the second works: a refusal after a tool ran is
319
+ thrown, with `kind: "context_overflow"`. So is one that shortening cannot fix. Even a recovery
320
+ costs a refused request and a step the user sees: declare the window instead.
321
+
322
+ ### Setting `tokenScale`
323
+
324
+ The documents are planned before the first request, with the scale the adapters declare. During a
325
+ question, the input tokens each provider reports raise the loop's estimate of each request's size,
326
+ and so leave less room, when they are higher than the scale says (up to twice the estimate). The
327
+ latest report counts: a lower one brings the estimate back down, but never below what the scale
328
+ says, nor, since 0.7.1, below what a request the provider refused as too large showed (up to 8
329
+ times the estimate, for the rest of the question: see
330
+ [a request too large for the model](../how-it-works.md#a-request-too-large-for-the-model)). A scale set too low makes requests that the provider can refuse as too large. A scale set too
331
+ high leaves part of the window unused.
332
+
333
+ To find the scale of an OpenAI-compatible model, compare its count of a sample of a file like the
334
+ ones your users upload, well inside the model's window (a few thousand lines), with the library's
335
+ estimate. It costs one request, whose reply you do not need:
336
+
337
+ ```ts
338
+ import { readFile } from "node:fs/promises";
339
+ import { estimateTokens } from "llm-large-files";
340
+ import { openAiCompatible } from "llm-large-files/openai";
341
+
342
+ const local = openAiCompatible({ baseUrl: process.env.LOCAL_LLM_URL!, model: process.env.LOCAL_LLM_MODEL! });
343
+ const text = (await readFile("sample.log", "utf8")).split("\n").slice(0, 5_000).join("\n");
344
+ const reply = await local.send({ system: "", messages: [{ role: "user", parts: [{ text }] }] });
345
+ console.log((reply.usage?.inputTokens ?? 0) / estimateTokens(text)); // about the tokenScale to set
346
+ ```
347
+
348
+ `gemini()` needs no scale. `anthropic()` defaults to 1.35, a cautious guess for Claude's tokenizer
349
+ ([Claude](./anthropic.md)).
350
+
351
+ ## Usage: what a question used
352
+
353
+ `result.usage` ([`UsageTotals`](../reference/ask.md#usagetotals)) sums every request of the
354
+ question that was answered, part reads included, in all and for each model:
355
+
356
+ | Field | What it counts |
357
+ |---|---|
358
+ | `requests` | Answered requests: chat requests and part reads. A request that failed and was sent again counts once. |
359
+ | `inputTokens` | Every token of the prompts, those read from a cache included. |
360
+ | `cachedInputTokens` | The part of `inputTokens` that was read from the provider's prompt cache. |
361
+ | `outputTokens` | Every token the models wrote, thoughts included. |
362
+ | `thoughtTokens` | The part of `outputTokens` spent thinking, where the provider says. |
363
+ | `byModel` | The same five counts for each model, keyed by the adapter's `id`. |
364
+
365
+ What each provider's numbers become:
366
+
367
+ | | Gemini | OpenAI-compatible | Claude |
368
+ |---|---|---|---|
369
+ | `inputTokens` | `promptTokenCount` + `toolUsePromptTokenCount` | `prompt_tokens` | `input_tokens` + `cache_creation_input_tokens` + `cache_read_input_tokens` |
370
+ | `cachedInputTokens` | `cachedContentTokenCount` | `prompt_tokens_details.cached_tokens`, or DeepSeek's `prompt_cache_hit_tokens` | `cache_read_input_tokens` |
371
+ | `outputTokens` | `candidatesTokenCount` + `thoughtsTokenCount` | `completion_tokens` | `output_tokens` |
372
+ | `thoughtTokens` | `thoughtsTokenCount` | `completion_tokens_details.reasoning_tokens` | 0: not reported |
373
+
374
+ - **Only answered requests are counted.** A request that failed is not, though the provider may
375
+ have billed it: a stream cut off half-way, or a wait on a silent model that ran out. Your
376
+ provider's bill is the record; `usage` is a close account of it.
377
+ - **A request without usage counts with 0 tokens**: an OpenAI-compatible server that sends no
378
+ usage, or a part reader of your own that does not call `onUsage`.
379
+ - **`byModel` is keyed by the adapter's `id`.** For `gemini()` that is the model named in the URL
380
+ (`"gemini-3.8-flash"`); for `openAiCompatible()` and `anthropic()`, the `model` option; for any of
381
+ them, the `id` option when you set it. A part read counts under the model that read it: the
382
+ explorer, when there is one. Two adapters with the same `id` share an entry, so give them their
383
+ own. `askGemini` names its models from their URLs and has no `id` option.
384
+ - **`turns` is not `usage.requests`.** `result.turns` counts the chat requests the question made,
385
+ part reads not included. `usage.requests` counts every answered request.
386
+ - **`lastUsage`** is the provider's own usage object of the last chat request, as it came.
387
+ - **A question that failed** throws. `partialResultOf(error)` gives what it had used until then.
388
+ - **A question planned again**, after the provider refused its first request as too large, counts
389
+ what its first try used.
390
+
391
+ ## Cost per user or per session
392
+
393
+ Add `result.usage` to the record of the chat session (or of the user) after each question, and
394
+ multiply by your prices. The library knows no prices: keep a price list for each model `id`, with
395
+ three rates: input not read from the cache, input read from the cache, and output. Thoughts are
396
+ part of `outputTokens`, so do not add `thoughtTokens` on top.
397
+
398
+ This module is the arithmetic. Save it as `usage.ts`:
399
+
400
+ ```ts
401
+ import type { ModelUsage, UsageTotals } from "llm-large-files";
402
+
403
+ /** One model's prices per million tokens, from your provider's price list. */
404
+ export type Price = { input: number; cachedInput: number; output: number };
405
+
406
+ /** One model's usage in a session. The model ID is a value, not a field name: IDs hold dots. */
407
+ export type ModelSpend = ModelUsage & { model: string; requests: number };
408
+
409
+ /** The usage part of your session record. */
410
+ export type SessionUsage = { questions: number; failed: number; cost: number; unpriced: string[]; models: ModelSpend[] };
411
+
412
+ export const noUsage = (): SessionUsage => ({ questions: 0, failed: 0, cost: 0, unpriced: [], models: [] });
413
+
414
+ /** What one question cost by your prices, and the models that have no price. */
415
+ export function costOf(usage: UsageTotals, prices: Record<string, Price>): { cost: number; unpriced: string[] } {
416
+ let cost = 0;
417
+ const unpriced: string[] = [];
418
+ for (const [model, used] of Object.entries(usage.byModel)) {
419
+ const price = prices[model];
420
+ if (!price) {
421
+ unpriced.push(model);
422
+ continue;
423
+ }
424
+ // inputTokens holds the cached tokens; outputTokens holds the thoughts.
425
+ const fresh = used.inputTokens - used.cachedInputTokens;
426
+ cost += (fresh * price.input + used.cachedInputTokens * price.cachedInput + used.outputTokens * price.output) / 1_000_000;
427
+ }
428
+ return { cost, unpriced };
429
+ }
430
+
431
+ /** A session's usage with one more question added. */
432
+ export function addUsage(session: SessionUsage, usage: UsageTotals, prices: Record<string, Price>, failed = false): SessionUsage {
433
+ const { cost, unpriced } = costOf(usage, prices);
434
+ const models = session.models.map((spend) => ({ ...spend }));
435
+ for (const [model, used] of Object.entries(usage.byModel)) {
436
+ let spend = models.find((known) => known.model === model);
437
+ if (!spend) {
438
+ spend = { model, requests: 0, inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, thoughtTokens: 0 };
439
+ models.push(spend);
440
+ }
441
+ spend.requests += used.requests;
442
+ spend.inputTokens += used.inputTokens;
443
+ spend.cachedInputTokens += used.cachedInputTokens;
444
+ spend.outputTokens += used.outputTokens;
445
+ spend.thoughtTokens += used.thoughtTokens;
446
+ }
447
+ return {
448
+ questions: session.questions + 1,
449
+ failed: session.failed + (failed ? 1 : 0),
450
+ cost: session.cost + cost,
451
+ unpriced: [...new Set([...session.unpriced, ...unpriced])],
452
+ models,
453
+ };
454
+ }
455
+ ```
456
+
457
+ Then the chat route records what each question used, the failed ones too:
458
+
459
+ ```ts
460
+ import { readFile } from "node:fs/promises";
461
+ import { partialResultOf, type ChatTurn, type ToolTurn, type UsageTotals } from "llm-large-files";
462
+ import { askGemini } from "llm-large-files/gemini";
463
+ import { addUsage, noUsage, type Price, type SessionUsage } from "./usage.js";
464
+
465
+ /** Your storage of chat sessions (MongoDB, SQL…): the usage is a field of the session record. */
466
+ export interface Sessions {
467
+ usage(userId: string, sessionId: string): Promise<SessionUsage | undefined>;
468
+ saveUsage(userId: string, sessionId: string, usage: SessionUsage): Promise<void>;
469
+ }
470
+
471
+ // Your price list, per million tokens: { "gemini-3.8-flash": { "input": …, "cachedInput": …, "output": … }, … }
472
+ const prices = JSON.parse(await readFile("./prices.json", "utf8")) as Record<string, Price>;
473
+
474
+ // files and endpoint as in the first sample. messages: the chat so far, ending with the question.
475
+ export async function answer(sessions: Sessions, userId: string, sessionId: string, documentIds: string[], messages: Array<ChatTurn | ToolTurn>) {
476
+ const record = async (usage: UsageTotals, failed: boolean) => {
477
+ const before = (await sessions.usage(userId, sessionId)) ?? noUsage();
478
+ await sessions.saveUsage(userId, sessionId, addUsage(before, usage, prices, failed));
479
+ };
480
+ try {
481
+ const result = await askGemini({ files, endpoint, owner: userId, documentIds, messages });
482
+ await record(result.usage, false);
483
+ return result;
484
+ } catch (error) {
485
+ // What the question paid for before it failed. Undefined when it failed before its first request.
486
+ const partial = partialResultOf(error);
487
+ if (partial) await record(partial.usage, true);
488
+ throw error;
489
+ }
490
+ }
491
+ ```
492
+
493
+ - **Failed questions cost too.** `partialResultOf(error)` holds the usage of a question that failed
494
+ once it was under way: a model error (its first request included, which then shows 0 requests),
495
+ or a question you cancelled. It is undefined for a question that failed before its first request
496
+ (a document that is gone, a budget that does not work), which used nothing.
497
+ - **Several servers.** Two questions of one session can end on two servers at the same moment, and
498
+ a read, an addition and a write lose one of them. Add with an atomic update of your database
499
+ (MongoDB's `$inc`, SQL's `UPDATE … SET n = n + ?`), or store one record per question and sum the
500
+ records when you need the total. Model IDs hold dots (`gemini-3.8-flash`), which MongoDB reads as
501
+ a path in an update, so keep them as values, as `models` does above, not as field names.
502
+ - **Claude's cache writes** are inside `inputTokens`, so the sample prices them at the plain input
503
+ rate, and Anthropic bills them at another. [Claude](./anthropic.md) shows how to read Claude's own
504
+ usage of each reply, which has them apart.
505
+ - **A price that depends on the size of each request** (a higher rate for a long prompt) cannot be
506
+ worked out from the totals of a question. Price each reply as it comes
507
+ ([below](#each-reply-as-it-comes)).
508
+
509
+ ### An allowance per user
510
+
511
+ To keep a user within an allowance, turn what the user has left into `limits.inputTokens` of the
512
+ next question. Keep a margin: a question can pass its ceiling by about two requests.
513
+
514
+ ```ts
515
+ import { askGemini } from "llm-large-files/gemini";
516
+
517
+ // files and endpoint as in the first sample. spentThisMonth: the user's input tokens this month,
518
+ // from your records. userId, documentIds and messages are yours.
519
+ const allowance = 50_000_000; // input tokens a month: your own figure
520
+ const margin = 2_000_000; // about two requests of a 1M-token window
521
+ const left = allowance - spentThisMonth;
522
+ if (left <= margin) throw new Error("You have used this month's allowance.");
523
+
524
+ const result = await askGemini({
525
+ files,
526
+ endpoint,
527
+ owner: userId,
528
+ documentIds,
529
+ messages,
530
+ limits: { inputTokens: Math.min(5_000_000, left - margin) },
531
+ });
532
+ ```
533
+
534
+ There is no limit across questions: each question runs up to four tool calls at a time, and each
535
+ whole-file read up to four parts at a time, whatever the other questions do. To bound how fast a
536
+ user or a tenant spends, wrap the adapters (below) and make them wait for your own limiter.
537
+
538
+ ### Each reply as it comes
539
+
540
+ With `askWithFiles`, an adapter you wrap sees the usage of every request it answers: its chat
541
+ requests and its part reads. Make the wrapped adapter for each question, so that what it reports
542
+ belongs to that question:
543
+
544
+ ```ts
545
+ import type { GenerateUsage, ModelAdapter } from "llm-large-files";
546
+
547
+ /** The adapter, with `onReply` called for every answered request: chat requests and part reads. */
548
+ export function metered(base: ModelAdapter, onReply: (model: string, usage: GenerateUsage) => void): ModelAdapter {
549
+ const { generateText } = base;
550
+ return {
551
+ ...base,
552
+ async send(request, hooks) {
553
+ const reply = await base.send(request, hooks);
554
+ onReply(base.id, reply.usage ?? {});
555
+ return reply;
556
+ },
557
+ ...(generateText ? {
558
+ generateText: (part) => generateText({
559
+ ...part,
560
+ onUsage: (used) => {
561
+ onReply(base.id, used);
562
+ part.onUsage?.(used); // the question's own count
563
+ },
564
+ }),
565
+ } : {}),
566
+ };
567
+ }
568
+ ```
569
+
570
+ `reply.providerUsage` of each chat request is the provider's own usage object, for the fields the
571
+ totals do not have. More on wrapping an adapter: [your own adapter and loop](./own-adapter-and-loop.md).
572
+
573
+ ## What costs most
574
+
575
+ ### Whole-file reads
576
+
577
+ - **A read sends the whole file once**, in parts of up to `mapChunkTokens` (and 80% of
578
+ `maxRequestBytes`), each line with its number. When the notes of the parts together are larger
579
+ than one part, it first merges them, in up to 8 rounds of merge requests. Then it writes an
580
+ answer. Its input is about the size of the file, and more for a file of many short lines. The
581
+ notes of a part may be up to 4,096 output tokens and the answer up to 8,192. For a model that
582
+ spends such a limit thinking, both are raised to 32,768.
583
+ - **With the defaults, one read can cost about 3,000,000 input tokens**: a file of up to 30 parts
584
+ of 100,000 tokens may be read whole. A file that needs more parts is not: its card says that it is
585
+ too large to be analyzed whole, and the tool is not offered when no file of the question can be
586
+ read whole.
587
+ - **Parts are read four at a time**, by the explorer model when there is one.
588
+
589
+ What bounds it:
590
+
591
+ - `limits.wholeDocumentReads` (1 per document by default), `wholeDocumentAnalysis: false`, and
592
+ `limits.inputTokens` and `limits.requests`, which refuse a read that would pass them.
593
+ - With your own loop, the same cap is `maxWholeDocumentReads` of `files.tools()`
594
+ (`MAX_WHOLE_DOCUMENT_READS`, 1, by default), counted per tool set: make one for each question
595
+ ([your own adapter and loop](./own-adapter-and-loop.md)).
596
+ - `budget.maxMapChunks`: with 10, only files of up to about 1,000,000 tokens are read whole at the
597
+ default part size.
598
+ - `budget.mapChunkTokens`: smaller parts give more detailed notes, and more requests, notes and
599
+ merges. The input of the parts is the file either way. With `maxMapChunks` it also sets the
600
+ largest file that is read whole.
601
+ - For a model that thinks, less thinking in the part reads: `analysisConfig` of `gemini()` and
602
+ `askGemini`, `analysisBody` of `openAiCompatible()` and `anthropic()`. See
603
+ [Vertex AI and Gemini](./vertex-and-gemini.md).
604
+
605
+ ### Long tool loops
606
+
607
+ Each chat request sends everything before it. One tool result may be up to `toolResultCharacters`
608
+ (24,000 characters, about 12,000 tokens of a log), up to 8 run in a turn, and every result stays in
609
+ the requests until the answer. Text tool results may fill the window up to
610
+ `contextTokens − reservedTokens / 2`: 968,000 tokens with the default budget. So the bound with the
611
+ defaults is 12 requests of up to about 968,000 tokens each, about 11.6 million input tokens, plus a
612
+ whole-file read of each document searched. A question of a few searches and reads is far from that
613
+ bound: [measurements](../measurements.md) has live numbers.
614
+
615
+ What bounds it: `limits.toolTurns` and `limits.callsPerTurn`; `limits.inputTokens`;
616
+ `budget.toolResultCharacters` (smaller results, though the model may then need more reads); and an
617
+ explorer model, which makes these requests at its own price.
618
+
619
+ ### Pages of PDFs
620
+
621
+ - **One `view_pages` call shows up to five pages** (`MAX_VIEW_PAGES`). A page costs about 530
622
+ tokens on Gemini, 1,000 on an OpenAI-compatible model and 3,500 on Claude by default (the
623
+ adapter's `pageTokens`). An OpenAI-compatible model is shown pages only with `pdfInput: true`.
624
+ Without it, `openAiCompatible()` declares `toolFiles: "none"`, and `view_pages` is offered to no
625
+ model of the question.
626
+ - **Pages stay in every later request of the question**, so a page shown early is paid for again
627
+ by each request after it. They are not kept in `toolTurns`, so a later question does not pay for
628
+ them again.
629
+ - **A question shows pages up to half of `reservedTokens`**, counted with the largest `pageTokens`
630
+ of its models: 60 pages on Gemini with the default budget, 32 on an OpenAI-compatible model with
631
+ `pdfInput`, 12 on Claude with the library's default window. The size of the request in bytes
632
+ bounds them too.
633
+
634
+ What bounds it: `viewPages: false`; `keepOriginals` only for the formats that need it (no kept
635
+ original, no pages); a smaller `reservedTokens`, which also keeps less of the window free for the
636
+ answer (text tool results may then grow the request further). See [PDFs](./pdfs.md).
637
+
638
+ ### Documents sent whole
639
+
640
+ Up to `inlineTokens` (200,000 by default) of document text goes into every chat request of the
641
+ question, and into every later question that names the same documents. Prompt caching makes the
642
+ repeats cheaper ([below](#prompt-caching)).
643
+
644
+ - A lower `inlineTokens` sends fewer documents whole. Each request is then smaller, but the model
645
+ needs tool turns to read what is searched: a question that one request answers from a document
646
+ sent whole can take several when the document is searched.
647
+ - Name in `documentIds` only the documents a question is about. Each one named is planned: sent
648
+ whole, or given a card.
649
+
650
+ ### An explorer model
651
+
652
+ With an explorer, the requests of the tool loop and the part reads go to a cheaper model, and the
653
+ model you chose for its answers is called once, with what the tools returned. A question that uses
654
+ the tools takes one request more. When that pays off: [explorer model](./explorer-model.md).
655
+
656
+ ## Prompt caching
657
+
658
+ A provider's prompt cache bills the start of a request it has seen recently at a lower rate, and
659
+ reports it in `cachedInputTokens`. The library keeps the start of the requests of a chat the same:
660
+
661
+ - **`documentPlacement: "first"`** (the default) puts the documents and cards at the start of the
662
+ first user turn, where they stay as the conversation grows, so every later request and every
663
+ follow-up question can read them from the cache. `"last"` appends them to the latest user turn:
664
+ they move with every question and are billed in full each time. In a live test with Gemini, 96%
665
+ of the input of a follow-up question was cached with `"first"`, against 0% with `"last"`
666
+ ([measurements](../measurements.md)).
667
+ - **Notes are not kept.** The note sent after an empty or broken turn, which asks the model to try
668
+ again, is in that one request only, and so is the note of the answer's second try. (When the
669
+ model that makes the tool calls has a conversation that may only grow, such as Claude, it keeps
670
+ the note of a broken tool turn.)
671
+ - **The request for the answer adds its line at the end.**
672
+
673
+ What you keep the same:
674
+
675
+ - **Your system instruction.** It comes first in every request, before the tool guide. A date, a
676
+ time or the user's question in it changes the start of every request, and nothing is read from
677
+ the cache. Put such things in the user's turn instead.
678
+ - **The documents, in the same order.** Their text and cards are in the order of `documentIds`.
679
+ Pass the same IDs in the same order. A document added to the chat changes the first user turn,
680
+ and the cache misses from there, once.
681
+ - **The history.** A turn you change or drop changes the request from that turn on
682
+ ([conversations](./conversations.md)).
683
+
684
+ What the library changes:
685
+
686
+ - A document that went whole can become a card as the history grows (above). The tool guide, which
687
+ names the files that are searched, changes with it.
688
+ - Within a question, when room runs short, older tool results are replaced by short stand-ins. The
689
+ request changes from the first round replaced. A model whose conversation may only grow (Claude)
690
+ has nothing replaced.
691
+ - The tool rounds of an earlier question are sent without their `tool_turns_left`. So the first
692
+ request of a follow-up question differs from the requests of the question before it from that
693
+ question's first tool round on, and the cache misses from there, once in each follow-up
694
+ question: those rounds are billed at the full price in that request (with Claude's
695
+ `cache_control`, as a cache write). The rounds of older questions were already sent without it,
696
+ and still match. The documents and cards before them are still read from the cache.
697
+ - An upgrade that changes the library's prompts misses the cache once in each conversation. 0.6.0
698
+ changed the tool guide, the descriptions of `search_document` and `analyze_whole_document`, and
699
+ the frame lines of a file sent whole. The first request after the upgrade shares with what 0.5.0
700
+ sent at most what comes before the first text that changed. For a question with files to
701
+ search, that is nothing on Claude and OpenAI-compatible endpoints, where the tools come first,
702
+ and at most your own system text on Gemini, where the tool guide follows it in the system
703
+ instruction. For a question whose files are all sent whole, it is your own system text, and
704
+ `view_pages` with its guide when the pages of a PDF can be looked at. From then on the frame of a
705
+ document is the same in every request
706
+ ([Deployment](./deployment.md#servers-of-two-versions)).
707
+
708
+ The adapters:
709
+
710
+ - `anthropic()` asks for caching: `cache` is `true` by default (five minutes), `"1h"` for an hour,
711
+ `false` for none. See [Claude](./anthropic.md).
712
+ - `gemini()` and `openAiCompatible()` send no cache settings. What the provider caches on its own
713
+ is reported in `cachedInputTokens`.
714
+
715
+ ## Related pages
716
+
717
+ - [`llm-large-files` reference: the tool loop](../reference/ask.md): `AskLimits`, `AskResult`,
718
+ `UsageTotals`, `ModelCapabilities`.
719
+ - [`llm-large-files` reference: the library](../reference/library.md): `Budget`, `DEFAULT_BUDGET`,
720
+ `resolveBudget`, `ModelLimits`, `budgetFor`.
721
+ - [Tools reference](../reference/tools.md): what each tool returns, `MAX_VIEW_PAGES`,
722
+ `MAX_WHOLE_DOCUMENT_READS`.
723
+ - [An explorer model](./explorer-model.md), [Vertex AI and Gemini](./vertex-and-gemini.md),
724
+ [OpenAI-compatible endpoints](./openai-compatible.md), [Claude](./anthropic.md).
725
+ - [Errors and reliability](./errors-and-reliability.md): requests too large, retries,
726
+ `partialResultOf`.
727
+ - [Conversations](./conversations.md): history, `toolTurns`, keeping the window.
728
+ - [How it works](../how-it-works.md): the room in the request and how the plan is made.