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
@@ -8,12 +8,13 @@ task, where there is one.
8
8
 
9
9
  ```ts
10
10
  import {
11
- askWithFiles, askStream, partialResultOf, DocumentsNotFoundError, UsageMeter,
12
- evidenceOf, mergeRanges, stubResult,
11
+ askWithFiles, askStream, partialResultOf, DocumentsNotFoundError, UsageMeter, TOOL_TURN_VERSION,
12
+ evidenceOf, mergeRanges, stubResult, DEFAULT_INPUT_TOKENS, answerInfoOf, checkCitations,
13
13
  EXPLORER_INSTRUCTION, FINAL_ANSWER_REQUEST, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_WITHOUT_TOOLS,
14
14
  } from "llm-large-files";
15
15
  import type {
16
- AskOptions, AskLimits, AskResult,
16
+ AskOptions, AskLimits, AskResult, MissingDocumentsAction, MissingDocumentsContext,
17
+ ToolResultContext, ToolResultVerdict, CitationCheck, AnswerInfo,
17
18
  ChatMessage, ChatTurn, ToolTurn,
18
19
  ModelAdapter, ModelCapabilities, ModelRequest, ModelMessage, ModelTextMessage, ModelToolRound,
19
20
  ModelPart, ToolCall, ToolAnswer, SendHooks, ModelReply, GenerateText, GenerateUsage,
@@ -30,7 +31,12 @@ Contents:
30
31
  [`askStream(options)`](#askstreamoptions), [`AskOptions`](#askoptions),
31
32
  [`AskLimits`](#asklimits), [`AskResult`](#askresult),
32
33
  [`partialResultOf(error)`](#partialresultoferror),
33
- [`DocumentsNotFoundError`](#documentsnotfounderror)
34
+ [`DocumentsNotFoundError`](#documentsnotfounderror), [missing documents](#missing-documents),
35
+ [`MissingDocumentsAction`](#missingdocumentsaction),
36
+ [`MissingDocumentsContext`](#missingdocumentscontext),
37
+ [`DEFAULT_INPUT_TOKENS`](#default_input_tokens),
38
+ [`ToolResultContext` and `ToolResultVerdict`](#toolresultcontext-and-toolresultverdict),
39
+ [`CitationCheck`](#citationcheck), [`AnswerInfo`](#answerinfo)
34
40
  - **What the loop adds to its requests:** [`EXPLORER_INSTRUCTION`](#explorer_instruction),
35
41
  [`FINAL_ANSWER_REQUEST`](#final_answer_request),
36
42
  [`FINAL_ANSWER_AFTER_PAGES`](#final_answer_after_pages),
@@ -76,24 +82,51 @@ What it does, in order:
76
82
  `options.budget` in place of its own, and fits it to what the adapters declare:
77
83
  `contextTokens`, `maxRequestBytes`, `tokenScale`, `outputTokens` (see
78
84
  [`ModelCapabilities`](#modelcapabilities)). `result.budget` is the outcome.
79
- 2. **Plans the documents** with `files.prepare`, for the room the conversation leaves. A document
80
- that is missing throws `DocumentsNotFoundError` before any model request.
81
- 3. **Sends one request without tools** to `model` when every document went in whole and no PDF
82
- can be looked at, and returns its reply.
85
+ 2. **Plans the documents** with `files.prepare`, for the room the conversation leaves. Documents
86
+ that are missing are settled by `onMissingDocuments` before any model request: by default the
87
+ question throws `DocumentsNotFoundError` ([missing documents](#missing-documents)).
88
+ 3. **Sends one request without tools** to `model` when every document went in whole, no PDF can be
89
+ looked at, and no table sent whole gets the tools (`inlineTables`), and returns its reply. So
90
+ it does when the tools are there only for tables sent whole and not one tool turn fits
91
+ (`limits.toolTurns: 1`, `limits.requests: 1`, or a ceiling with room for one request): the
92
+ request of `"text"`, with no notice (since 0.10.0).
83
93
  4. **Otherwise runs tool rounds.** The model that explores (`explorer`, or `model` without one)
84
- gets the tools. Of each turn's calls, the loop runs at most `limits.callsPerTurn`, up to four
85
- at a time, each result fitted to the room left in the request, and sends the results back.
86
- Tools run in at most `limits.toolTurns - 1` model turns.
94
+ gets the tools; `model` does when no file is searched and the tools are there for tables sent
95
+ whole (since 0.10.0). Of each turn's calls, the loop runs at most `limits.callsPerTurn`, up to
96
+ four at a time, each result fitted to the room left in the request, and sends the results back.
97
+ Tools run in at most `limits.toolTurns - 1` model turns. Before each tool request it checks the
98
+ ceiling of the question ([`AskLimits`](#asklimits)): when what was spent, that request and the
99
+ answer's request would pass it, the next request is the answer.
87
100
  5. **Ends with the answer.** A reply with text and no tool call is the answer, when there is no
88
- explorer. Otherwise (out of turns, room or `limits`, a reply with no text, an explorer that is
89
- done) `model` gets one more request: the tools listed, `toolChoice: "none"`, and one of the
90
- [`FINAL_ANSWER_*`](#final_answer_request) lines as a user turn at the end. When its reply has
91
- no text (it is empty, or holds a tool call the model was told not to make), that request is
92
- sent once more with a note after the line, which is not kept: "Your last reply had no text. No
93
- tool can be called in this reply: write the answer now, in text, from what is above." Not after
94
- a refusal (`blockReason`), a reply `"filtered"`, or one `"cut"` with nothing in it; not once
95
- `limits.requests` or `limits.inputTokens` is reached; and not when the question already made its
96
- two second tries (see [`ModelReply`](#modelreply)). New in 0.6.0.
101
+ explorer. A turn whose tool call could not be read (`finish: "malformed_call"`) is not, even
102
+ with a remark in it (since 0.10.0). Otherwise (out of turns, room or `limits`, a reply with no
103
+ text, an explorer that is done) `model` gets one more request: the tools listed,
104
+ `toolChoice: "none"`, and one of the [`FINAL_ANSWER_*`](#final_answer_request) lines as a user
105
+ turn at the end. When its reply has no text (it is empty, or holds a tool call the model was
106
+ told not to make), that request is sent once more with a note after the line, which is not
107
+ kept: "Your last reply had no text. No tool can be called in this reply: write the answer now,
108
+ in text, from what is above." Not after a refusal (`blockReason`), a reply `"filtered"` or
109
+ `"other"`, or one `"cut"` with nothing in it; not once `limits.requests` or the ceiling of input
110
+ tokens is reached; and not when the question already made its two second tries (see
111
+ [`ModelReply`](#modelreply)). New in 0.6.0. When the tools are there only for tables sent whole,
112
+ a turn with no call whose reply is `"filtered"` or `"other"` with no text, or `"cut"` before any
113
+ text, ends the question without this request, as the request of step 3 would end (since 0.10.0).
114
+ 6. **Says how the answer ended.** `result.finish` is the `finish` of the reply whose text is the
115
+ answer, or of the last reply when none answered. A `"filtered"` answer has an `answer_filtered`
116
+ notice, a `"cut"` one an `answer_cut` notice, before `run.finish`; `filteredAnswer: "drop"`
117
+ drops a filtered answer. `result.citations` checks the answer's line citations against the
118
+ evidence. [`answerInfoOf`](#answerinfo) turns the result into the reason to show. New in 0.10.0.
119
+
120
+ A call of a tool the question does not have is not run, and takes no room in the request: it is
121
+ answered `Unknown tool “name”. The tools are: search_document, read_document, …`, and its
122
+ `tool.end` has outcome `"refused"`. Until 0.10.0 it was run, and given room at the cap of a
123
+ result, so a turn of such calls shortened the results of earlier turns for nothing.
124
+
125
+ The room for tool results is counted in tokens (since 0.10.0): each result at its document's own
126
+ characters per token (`characters` / `estimatedTokens`, from 0.8 to 4), not at 2 for every file. A
127
+ table of numbers takes about one token a character, and its results took twice their room. A
128
+ result that would still pass the room (a guess that came out low, or a tool set of your own that
129
+ does not keep to `maxResultCharacters`) is cut, in call order, before the model gets it.
97
130
 
98
131
  A request that fails is sent again by the rule of `retry` (see
99
132
  [`withRetry`](./errors-and-retries.md#withretryrun-options)), but never once text of its reply was
@@ -106,6 +139,16 @@ the provider allows (OpenAI's and Groq's TPM, HTTP 429 or 413) is this kind too,
106
139
  allowance as the window, and its steps say so.
107
140
  [How it works](../how-it-works.md#a-request-too-large-for-the-model) explains each step.
108
141
 
142
+ New in 0.9.0: the first request of a question is not sent to be refused. When the stored rounds of
143
+ earlier questions make it larger than the room it has in tokens, by the loop's own estimate (the
144
+ window less half of `reservedTokens`), their results are shortened first, in the same steps, until
145
+ it fits. The request is then what 0.8.2 sent again after the provider refused it, without the
146
+ refused request before it. Only tokens are counted here, as in that recovery: a request is not
147
+ shortened for its bytes alone. This is done for an `appendOnly` model too: a stored round has no
148
+ thinking in it, and nothing of the question was sent yet. Before, such a question failed on Claude.
149
+ `steps` says "Older tool results were shortened to make room in the request", once: a question
150
+ planned again shortens them again without saying so twice.
151
+
109
152
  **Returns** an [`AskResult`](#askresult).
110
153
 
111
154
  **Throws:**
@@ -116,11 +159,17 @@ allowance as the window, and its steps say so.
116
159
  | `Error`: "The last message must be the user's." | `messages` is empty, or its last message is not a user turn. | undefined |
117
160
  | `RangeError`: "limits.… must be a number, and is NaN. Leave it out for the default.", or `TypeError`: "limits.… must be a number, and is …" | A field of `options.limits` is NaN, or not a number. Before any request. New in 0.7.1. | undefined |
118
161
  | [`DocumentStoreError`](./library.md#documentstoreerror) | The store could not be read while the documents were planned. The documents are not gone: try again. A store that fails during a tool call is not thrown: the model gets the message as the tool's `error`. | undefined |
119
- | [`DocumentsNotFoundError`](#documentsnotfounderror) | A document of `documentIds` was never stored, has expired or been deleted, or belongs to another `owner`. Before any request. | undefined |
162
+ | What a tool call rejected with | The tool set's `executeWithFiles` rejected: the question ends with it, and the model gets nothing of it. The calls of the turn still running stop. A store call that timed out inside a tool is thrown this way. | What the question had done |
163
+ | What `onToolResult` threw, or `TypeError`: "onToolResult returned …: it must return { result }, { reject: "why" } or undefined." | The hook threw, its promise rejected, or it returned another shape. The result is not sent. New in 0.10.0. | What the question had done |
164
+ | [`DocumentsNotFoundError`](#documentsnotfounderror) | A document of `documentIds` was never stored, has expired or been deleted, or belongs to another `owner` or `scope`, and `onMissingDocuments` is `"throw"` (the default) or returned it; or a retry or replace of `onMissingDocuments` did not bring it back. Before any request. | undefined |
165
+ | `TypeError`: "onMissingDocuments must be "throw", "drop" or a function, and is …", or "onMissingDocuments returned …: it must return …" | `onMissingDocuments` is something else, or its function returned something else. New in 0.9.0. | undefined |
166
+ | What the function of `onMissingDocuments` threw | It threw, or its promise rejected. Before any request. New in 0.9.0. | undefined |
167
+ | `TypeError("owner is required: requireOwner is on")`, `TypeError("scope is required: requireScope is on")` | The library requires an owner or a scope ([`LargeFilesOptions`](./library.md#largefilesoptions)), and the question has none. Before any request. New in 0.9.0. | undefined |
168
+ | [`DocumentScopeError`](./library.md#documentscopeerror) | `scope` is not a valid scope, or the store threw one. Before any request when the scope is not valid. New in 0.9.0. | undefined |
120
169
  | [`ModelRequestError`](./errors-and-retries.md#modelrequesterror), or the adapter's subclass (`GeminiRequestError`, `OpenAiRequestError`, `AnthropicRequestError`) | A chat request failed, and was not worth another try, still failed after `retry.retries` more, asked for a longer wait than `retry.maxDelayMs`, or had already shown text. A `context_overflow` that the recovery above did not mend. | What the question had done |
121
170
  | Any other error of an adapter | Thrown as it came. An error without a numeric `status` is not sent again. | What the question had done |
122
171
  | What a listener threw | `onEvent`, `onText`, `onActivity` or `onStep` threw. The question stops: the calls of the turn still running stop, and no request follows. New in 0.7.0 for a throw during a whole-file read (`onActivity` on its progress, `onEvent` on its events): 0.6.0 reported it to the model as the tool's error, and went on. | What the question had done, when the error is an object and the question was under way |
123
- | The signal's reason | `signal` aborted. Nothing is sent or retried after that, no part of a whole-file read either. It is thrown at once, also while an adapter (or a part reader) that does not look at the signal is still at work, and also when the adapter then fails with its own error. Text that such an adapter sends later is not shown. | What the question had done, when the reason is an object that no other question threw too (see [`partialResultOf`](#partialresultoferror)) |
172
+ | The signal's reason | `signal` aborted. Nothing is sent or retried after that, no part of a whole-file read either. It is thrown at once, also while an adapter (or a part reader) that does not look at the signal is still at work, and also when the adapter then fails with its own error. Text that such an adapter sends later is not shown. Since 0.10.0 also while `files.prepare`, a tool call or `onToolResult` waits: on a store that hangs, with any `LargeFiles`. | What the question had done, when the reason is an object that no other question threw too (see [`partialResultOf`](#partialresultoferror)) |
124
173
 
125
174
  When the documents were planned again after an overflow and the second plan fails before it sends
126
175
  anything, the first overflow error is thrown, with what the first try had done. A whole-file part
@@ -229,17 +278,21 @@ The options of `askWithFiles`.
229
278
  |---|---|---|---|
230
279
  | `files` | [`LargeFiles`](./library.md#largefiles) | required | The library that holds the documents, plans them and makes the tools. |
231
280
  | `model` | [`ModelAdapter`](#modeladapter) | required | The model that answers. Without `explorer`, it also makes the tool calls and reads whole files in parts. |
232
- | `explorer` | `ModelAdapter \| undefined` | none | A second model, of any provider, that makes the tool calls (search, read, look at pages) and reads whole files in parts. `model` then writes the answer from what the tools returned. Its requests get [`EXPLORER_INSTRUCTION`](#explorer_instruction), and its text is not shown. Left out, or the same object as `model`: one model does both. |
233
- | `documentIds` | `string[]` | required | The documents this question may use. Duplicates count once. One that is missing throws [`DocumentsNotFoundError`](#documentsnotfounderror). |
281
+ | `explorer` | `ModelAdapter \| undefined` | none | A second model, of any provider, that makes the tool calls (search, read, look at pages) and reads whole files in parts. `model` then writes the answer from what the tools returned. Its requests get [`EXPLORER_INSTRUCTION`](#explorer_instruction), and its text is not shown. Left out, or the same object as `model`: one model does both. A question in which no file is searched and the tools are there for tables sent whole (`inlineTables`) does not use it: `model` runs the tools (since 0.10.0). |
282
+ | `documentIds` | `string[]` | required | The documents this question may use. Duplicates count once. One that is missing throws [`DocumentsNotFoundError`](#documentsnotfounderror), unless `onMissingDocuments` says otherwise. |
234
283
  | `messages` | [`ChatMessage[]`](#chatmessage) | required | The conversation, oldest first. The last message must be the user's question. The loop works on copies: your array is not changed. |
235
284
  | `documentPlacement` | `"first" \| "last"` | `"first"` | Where document text and cards go. `"first"`: at the start of the first user turn, where they stay as the conversation grows, so the provider's prompt cache can reuse them on every follow-up question. `"last"`: after the text of the latest user turn; they then move on every turn and are billed in full each time. |
236
285
  | `system` | `string` | none | Your system instruction. It is trimmed, and the guide to the document tools is added after it when a document is reached through tools or has pages to look at. |
237
286
  | `owner` | `string` | none | The user (or tenant) asking. A document ingested with another owner is treated as missing. Without `owner`, only documents ingested without one can be used. |
287
+ | `scope` | [`DocumentScope`](./library.md#documentscope) | none | The scope of the question, such as `[userId, chatId]`. Every store call of the question carries it, and a document ingested with another scope is treated as missing. The tools check the owner and scope the store holds against `owner` and `scope` (`ToolOptions.access`). New in 0.9.0. |
288
+ | `onMissingDocuments` | `"throw" \| "drop" \| ((missing: string[], context: MissingDocumentsContext) => MissingDocumentsAction \| Promise<MissingDocumentsAction>)` | `"throw"` | What to do when documents of `documentIds` are missing: expired, deleted, never stored, or of another owner or scope, which look the same. Settled before any request. `"throw"`: [`DocumentsNotFoundError`](#documentsnotfounderror), as before 0.9.0. `"drop"`: the question is answered without them. A function: it gets the missing IDs, and says what to do. See [missing documents](#missing-documents). New in 0.9.0. |
238
289
  | `limits` | [`AskLimits`](#asklimits) | `{}` | The limits of this question: tool turns, calls per turn, whole-file reads, ceilings on tokens and requests. |
239
290
  | `retry` | [`RetryOptions`](./errors-and-retries.md#retryoptions) | `{ retries: 3, baseDelayMs: 500, maxDelayMs: 60_000 }` | How a failed model request is sent again: chat requests and whole-file part reads. `{ retries: 0 }` turns it off. |
240
291
  | `budget` | `Partial<`[`Budget`](./library.md#budget)`>` | the library's | Budget fields for this question, in place of the library's. Fields given nowhere follow the context window. The budget is then fitted to the models either way: `result.budget` shows it. |
241
292
  | `wholeDocumentAnalysis` | `boolean` | `true` | Offer `analyze_whole_document`, which reads a whole file in many model requests. It is offered only when the model that explores has `generateText` and a document reached through tools is small enough to be read in about `budget.maxMapChunks` parts or fewer. `false` withholds it. The tool guide names it only when it is offered, and a card offers it only for a file that is small enough. With `false`, or a model that explores without `generateText`, a card says that its file can be searched and read by line ranges, not that it can be analyzed whole or is too large for that. |
242
293
  | `viewPages` | `boolean` | `true` | Offer `view_pages` for PDFs whose original file is kept (`keepOriginals`). It is offered only when no model of the question has `capabilities.toolFiles: "none"`. It changes nothing for a library that keeps no originals. |
294
+ | `inlineTables` | `"tools" \| "text"` | `"tools"` | `"tools"`: a table sent whole can still be counted and searched. A CSV or an XLSX workbook, or a DOCX, PPTX, PDF, HTML or Markdown file with a table of at least 3 `\| cell \|` rows, gets `search_document`, `read_document` and `aggregate_table` (not `get_document_overview`, not `analyze_whole_document`), its frame line its `document_id` for them, and the system text a line that says to count with them. The question then runs the tool loop: one that needs no count is answered in its first request, a count takes about 3. When not one tool turn fits the `limits`, it is the one request of `"text"`. When no file is searched, `model` runs that loop itself and `explorer` gets no request. `"text"`: it is sent whole without tools, as in 0.9. Another value is a `TypeError` before any request. See [the cost of tables sent whole](../guides/costs-and-limits.md#tables-sent-whole). New in 0.10.0. |
295
+ | `numberInline` | `boolean` | `true` | Number the lines of the files sent whole, as the tools number them (`12\| `), so that the answer can cite them and `result.citations` can check it. Each such file is planned at its numbered size, 8% to 16% more tokens, so a file at the edge of `inlineTokens` may become a card. When no file is searched, the system text gets the line `Cite line numbers like (report.docx L12).` `false` sends them as in 0.9; with `inlineTables: "text"` too, the requests are those of 0.9, byte for byte. Another value is a `TypeError` before any request. New in 0.10.0. |
243
296
  | `onText` | `(delta: string) => void` | none | The answer's text as it arrives. With it, `streamText` defaults to `true`, and the adapter streams when it can; otherwise the text of each reply comes once the reply is in: in one piece, or from `gemini()`, one piece for each text part. A remark the model wrote before a tool call comes too, and the text of a later reply then starts with `"\n\n"`. With an explorer, only the answering model's text comes. |
244
297
  | `streamText` | `boolean` | `true` with `onText`, and in [`askStream`](#askstreamoptions); `false` otherwise | Whether to ask the model for the answer as it is written: the loop then passes `onText` to the adapter's `send` ([`SendHooks`](#sendhooks)), and an adapter that can stream does. A reply that fails after its first piece of text is not sent again: that text was shown. With `false`, the text of each reply comes once the reply is in, to `onText` and as `text` events, and a reply that fails can be sent again. A listener of the events alone (`onEvent` without `onText`) does not change how the model is asked. New in 0.7.0. |
245
298
  | `onActivity` | `(text: string) => void` | none | Short-lived status in English: each tool call as it starts ("Search app.log (exact) for “timeout”…"), "Too large to read at once: app.log. Searching instead…", the progress of a whole-file read, a retry of a chat request ("The model did not answer (HTTP 503). Trying again in 2 s…", "The model could not be reached. Trying again…", or, for a reply that began and was cut off on its way, "The model's reply was cut off on its way. Trying again…"), and "Writing the answer…" before the request for the answer. Show it as plain text: a tool call's line can quote the model's words. The retries of a whole-file read's requests are not told here: they come only as `retry` events. |
@@ -247,7 +300,9 @@ The options of `askWithFiles`.
247
300
  | `onEvent` | `(event: AskEvent) => void` | none | Everything the question does, as typed events in order: `run.start`, the `plan`, each model request (`request.start`, `retry`, `request.end`), each tool call (`tool.start`, `tool.progress`, `tool.end`), the text, the notices, and last `run.finish` or `run.error`. See [events](./events.md). `onText`, `onActivity` and `onStep` still get the same strings, at the same moments. A model error in an event is told by its kind and status, never in the provider's words ([`EventError`](./errors-and-retries.md#errors-in-events-eventerror)). Tool results are left out unless `eventResults` is set. A throw from it ends the question with that error ([a listener that throws](./events.md#a-listener-that-throws)). New in 0.7.0. |
248
301
  | `runId` | `string` | `"run_"` and 16 hex digits | The `runId` of every event of the question. Pass your own to find the events in your logs. New in 0.7.0. |
249
302
  | `eventResults` | `boolean` | `false` | Put each tool result in its `tool.end` event (`result`), and `toolTurns` in the result that `run.finish` and `run.error` carry. Off by default: results hold the text of the documents, and events are often sent on to a browser. The result `askWithFiles` returns always has `toolTurns`. New in 0.7.0. |
250
- | `signal` | `AbortSignal` | none | Stops the question: the request under way is aborted through the adapter, tool calls stop, and nothing is sent again. `askWithFiles` then throws the signal's reason, at once: the loop does not wait for an adapter, or a part reader, that does not look at the signal. A request left running that way may be billed by the provider, and is not counted in the usage. |
303
+ | `filteredAnswer` | `"keep" \| "drop"` | `"keep"` | What to do with an answer that a filter of the provider stopped (`result.finish` `"filtered"`). `"keep"` keeps its text, as in 0.9, with `answered: true` when it has some. `"drop"` gives `answered: false` and `text: ""`. Text that was already sent (`onText`, `text` events) cannot be taken back: the `answer_filtered` notice then has `discardText: true`, before `run.finish`, and the page takes the text away. Text of a reply that was not streamed is not sent at all. Any other value (`"Drop"`, `true`) is a `TypeError` before any request: it would keep an answer that was meant to be dropped. See [filtered and cut answers](../guides/errors-and-reliability.md#filtered-and-cut-answers). New in 0.10.0. |
304
+ | `onToolResult` | `(context: ToolResultContext) => ToolResultVerdict \| undefined \| Promise<ToolResultVerdict \| undefined>` | none | Called with the result of every tool call that ran, as soon as it is in (the hooks of one turn may run at the same time), before the model, the evidence, the steps and the events get it ([`ToolResultContext` and `ToolResultVerdict`](#toolresultcontext-and-toolresultverdict)). A call that was refused, not run, or answered with a pointer is not passed to it. What it throws, or a value of another shape, ends the question. For data loss prevention: [security](../security.md#tool-results-ontoolresult). New in 0.10.0. |
305
+ | `signal` | `AbortSignal` | none | Stops the question: the request under way is aborted through the adapter, tool calls stop, and nothing is sent again. `askWithFiles` then throws the signal's reason, at once: the loop does not wait for an adapter, or a part reader, that does not look at the signal. A request left running that way may be billed by the provider, and is not counted in the usage. Since 0.10.0 the loop does not wait either for `files.prepare`, a tool call or `onToolResult` once it aborts, and it passes the signal on with the access of the question (`PrepareOptions.signal`, `ToolOptions.access.signal`), for a library that ends its own waits for the store with it. |
251
306
 
252
307
  Guides: [conversations](../guides/conversations.md) (`messages`, `documentPlacement`),
253
308
  [storage](../guides/storage.md) (`owner`), [web app](../guides/web-app.md) (`onText`,
@@ -265,11 +320,20 @@ every tool. `Infinity` sets no ceiling.
265
320
 
266
321
  | Field | Type | Default | What it does |
267
322
  |---|---|---|---|
268
- | `toolTurns` | `number` | 12 | The most model turns of the chat for one question, counting the answer and a second try after an empty or broken reply. Tools run in all but the last: if the model is still calling tools then, the last turn must be answered in text. With an explorer, the explorer has up to `toolTurns - 1` turns and `model` the last. A request the provider refused as too large takes no turn of its own: what is sent again after it is the same turn, so `result.turns` can be a little higher. When the answer comes back without text, it is asked for once more, and that request can be one past `toolTurns`; it is not made once `requests` or `inputTokens` is reached. Truncated to a whole number; below 1 counts as 1. With 1, no tool runs and the only request is the answer. |
323
+ | `toolTurns` | `number` | 12 | The most model turns of the chat for one question, counting the answer and a second try after an empty or broken reply. Tools run in all but the last: if the model is still calling tools then, the last turn must be answered in text. With an explorer, the explorer has up to `toolTurns - 1` turns and `model` the last. A request the provider refused as too large takes no turn of its own: what is sent again after it is the same turn, so `result.turns` can be a little higher. When the answer comes back without text, it is asked for once more, and that request can be one past `toolTurns`; it is not made once `requests` or the ceiling of input tokens is reached. Truncated to a whole number; below 1 counts as 1. With 1, no tool runs and the only request is the answer. |
269
324
  | `callsPerTurn` | `number` | 8 | The most tool calls of one model turn that are run. Each call beyond it is answered with an error ("Not run: one turn runs at most 8 tool calls. Send this call again if you still need it."), and `steps` says how many were not run. Truncated to a whole number; below 1 counts as 1. |
270
325
  | `wholeDocumentReads` | `number` | 1 ([`MAX_WHOLE_DOCUMENT_READS`](./tools.md#max_whole_document_reads)) | How many times each document may be read whole (`analyze_whole_document`) in one question. One read of a large file is up to `budget.maxMapChunks` part requests and a few more. 0 refuses every whole-file read but still lists the tool: to withhold it, set `wholeDocumentAnalysis: false`. |
271
- | `inputTokens` | `number` | none | A ceiling on the input tokens of the question, over all its requests, part reads included, as the adapters report them (`usage.inputTokens`, cached tokens included). Checked before each tool request: once it is reached, no further tool request is made and the next request is the answer. The calls of the reply that reached it still run, and their results and the answer come on top. A whole-file read that would pass it is refused, with the numbers, before it starts. |
326
+ | `inputTokens` | `number` | see below | A ceiling on the input tokens of the question, over all its requests, part reads included, as the adapters report them (`usage.inputTokens`, cached tokens included), and by the library's estimate for a request that reports no input (`usage.estimatedInputTokens`, since 0.10.0). Checked before each tool request, looking ahead (since 0.10.0): when what was spent, that request and the answer's request, as the loop estimates them now, would pass it, no further tool request is made and the next request is the answer. So the question spends at most about one request past it: the answer's, with the results of the last turn in it. A whole-file read that would pass it is refused, with the numbers, before it starts: priced with its line numbers, prompts and merges of notes since 0.10.0. `Infinity`: no ceiling, as before 0.10.0. |
272
327
  | `requests` | `number` | none | The same ceiling on model requests, chat requests and part reads together, as `usage.requests` counts them. Once `requests - 1` are used, no further tool request is made: the last request is kept for the answer. The calls of the reply that used it still run, but a whole-file read that needs more requests than are left is refused, and the reads of one turn share what is left. |
328
+ | `wholeReadsPerQuestion` | `number` | 2 | How many whole-file reads one question may make over all its documents, next to `wholeDocumentReads` for each one. A read that sent requests counts, one that read no part among them; a read refused before it starts does not. A read past it is refused: "Not run: one question makes at most 2 whole-file reads, and this one has made them. Use search_document and read_document on app.log." Truncated to a whole number. `Infinity` keeps the rule of 0.9, one read of each document. New in 0.10.0. |
329
+
330
+ **The default ceiling** (new in 0.10.0). A question that sets no `inputTokens` has one: the larger
331
+ of [`DEFAULT_INPUT_TOKENS`](#default_input_tokens) (1,000,000) and `toolTurns` times the estimate
332
+ of its first request, plus room for its whole-file reads. That room is as many reads as
333
+ `wholeReadsPerQuestion` and the documents that can be read whole allow (`wholeDocumentReads` of
334
+ each), each at the price of the dearest of them, and 0 when no document can be read whole. So a
335
+ read of a 1.77 MB log, about 1.5M tokens, still runs, and a question of 4 tool turns over a 3 MB log
336
+ does not come near the ceiling. Set `inputTokens: Infinity` for the behavior of 0.9.
273
337
 
274
338
  `askGemini` also takes `maxToolTurns` and `maxToolCallsPerTurn`, the names these had before 0.5.0
275
339
  (see [gemini](./gemini.md)). Guide: [costs and limits](../guides/costs-and-limits.md).
@@ -282,17 +346,20 @@ question that failed.
282
346
  | Field | Type | What it holds |
283
347
  |---|---|---|
284
348
  | `text` | `string` | Everything the answering model wrote, as `onText` got it: a remark made before a tool call, then `"\n\n"` and the answer. With an explorer, only what `model` wrote. `""` when nothing was written. |
285
- | `answered` | `boolean` | True when the last reply had text that is not blank, and the provider did not refuse the prompt. False when the prompt was refused (`blockReason`), or the last reply had no text: it was cut off before any text, or the request for the answer came back without text, and so did its second try. `text` may then be empty, or hold a remark made before a tool call, or the start of a reply that was refused: show your own message. |
349
+ | `answered` | `boolean` | True when the last reply had text that is not blank, and the provider did not refuse the prompt. False when the prompt was refused (`blockReason`), or the last reply had no text: it was cut off or filtered before any text, or the request for the answer came back without text, and so did its second try. A turn whose tool call could not be read is not the answer, even with a remark in it: the answer is asked for (since 0.10.0; before, the remark was the answer). With `filteredAnswer: "drop"`, false for a filtered answer. `text` may then be empty, or hold a remark made before a tool call, or the start of a reply that was refused: show your own message ([`answerInfoOf`](#answerinfo) says which). |
286
350
  | `blockReason` | `string`, optional | Why the provider refused the prompt, in the adapter's words. Set only then. Nothing more is asked after a refusal. |
287
351
  | `steps` | `string[]` | Each finished step, in order: a line for each tool call, run or refused ("Search app.log (exact) for “timeout” — 12 matching lines", or "… — already shown above"), one for the calls of a turn over `callsPerTurn`, and one when the loop shortened older results, asked again after an empty or broken reply, or planned the documents again. The second try of the answer says "The model's answer was empty: it was asked again" or "The model called a tool instead of answering: it was asked again for the answer". The lines `onStep` got. Each is one line of plain text: a line break, a tab or another control character in what the model sent becomes one space with the blanks around it; the invisible characters that file text loses are dropped (text-direction overrides and isolates, zero-width spaces, word joiners, soft hyphens, tag characters); `](` becomes `] (`, so that a markdown link or picture stays text. A query is cut at 80 characters and a task at 100, never in the middle of a character. Steps still quote the model's words, HTML tags and web addresses included: show them as plain text, never as markdown or HTML. |
288
- | `evidence` | [`Evidence[]`](#evidence) | What each tool call showed the model: the document, and the lines or pages. In call order. A call that failed, was not run, or was answered with a pointer to an earlier result adds none. Each has the `callId` of its call's events (new in 0.7.0). |
352
+ | `evidence` | [`Evidence[]`](#evidence) | What the model was shown. First each file sent whole, in the order of its block: `{ tool: "inline", documentId, document, lines: [[1, lines]], whole: true }`, with no `callId` (new in 0.10.0). Then what each tool call showed: the document, and the lines or pages, in call order. A call that failed, was not run, or was answered with a pointer to an earlier result adds none. Each of those has the `callId` of its call's events (new in 0.7.0). |
289
353
  | `toolTurns` | [`ToolTurn[]`](#toolturn) | The tool rounds of this question, as plain JSON, as the model last had them. Pass them back in `messages`, between this question and its answer, and a later question sees what was found here. Each result of a call made in this question has `tool_turns_left`, except a stand-in (`dropped: true`, see [`stubResult`](#stubresultcall-result-hadfiles)): a result shortened to make room, a pointer whose result was shortened, and the result of a call that showed pages. The pages are not kept: their stand-in says which pages were shown. A call's `problem` is left out. |
290
354
  | `plan` | [`DocumentPlan`](./library.md#documentplan) | Which documents went in whole (`inline`) and which were reached through tools (`searchable`). |
355
+ | `missing` | `string[]`, optional | The documents of `documentIds` that were missing, and that the question was answered without (`onMissingDocuments` `"drop"`). Absent when none was. New in 0.9.0. |
291
356
  | `budget` | [`Budget`](./library.md#budget) | The budget the question ran with: the library's (with `options.budget`), fitted to the models. |
292
357
  | `turns` | `number` | Chat requests of the question, the explorer's among them; whole-file part reads are not counted. A request counts when it is sent, so one that failed counts too. One sent again after a failure counts once; one sent again smaller after an overflow counts again. |
293
358
  | `finishReason` | `string`, optional | The provider's own word for why the last reply that gave one ended (`"STOP"`, `"length"`, `"end_turn"`). |
294
- | `usage` | [`UsageTotals`](#usagetotals) | Tokens and requests of the whole question, whole-file part reads included, in all and for each model by its `id`. |
359
+ | `usage` | [`UsageTotals`](#usagetotals) | Tokens and requests of the whole question, whole-file part reads included, in all and for each model by its `id`. The input of requests that reported none is in `estimatedInputTokens`. |
295
360
  | `lastUsage` | `Record<string, unknown>`, optional | The provider's own usage object of the last chat reply that had one, as it came. |
361
+ | `finish` | `"complete" \| "cut" \| "filtered" \| "malformed_call" \| "other"`, optional | How the reply whose text is the answer ended (`ModelReply.finish`), or the last reply of the chat when none answered. Absent when the adapter does not say. `"filtered"` and `"cut"` come with an `answer_filtered` or `answer_cut` notice. New in 0.10.0. |
362
+ | `citations` | [`CitationCheck`](#citationcheck), optional | The line citations of `text`, checked against the evidence of the question: a document sent whole, or read whole, counts as shown, every line it has. Set when the question had documents. New in 0.10.0. |
296
363
 
297
364
  Guides: [conversations](../guides/conversations.md) (`toolTurns`),
298
365
  [costs and limits](../guides/costs-and-limits.md) (`usage`),
@@ -339,17 +406,283 @@ Guide: [errors and reliability](../guides/errors-and-reliability.md).
339
406
  declare class DocumentsNotFoundError extends Error {
340
407
  constructor(ids: string[]);
341
408
  readonly ids: string[];
409
+ readonly code: "documents_missing"; // new in 0.9.0
410
+ readonly status: 404; // new in 0.9.0
411
+ static is(value: unknown): value is DocumentsNotFoundError; // new in 0.9.0
342
412
  }
343
413
  ```
344
414
 
345
415
  Thrown by `askWithFiles` (and `askGemini`) before any model request, when documents of
346
- `documentIds` were never stored, have expired or been deleted, or belong to another owner. `ids`
416
+ `documentIds` were never stored, have expired or been deleted, or belong to another owner or scope. `ids`
347
417
  lists them. `name` is `"DocumentsNotFoundError"`. The message names the IDs, not the files: "A
348
418
  document is no longer available: ‹id›. Upload it again.", or for several "3 documents are no longer
349
- available: ‹id›, ‹id›, ‹id›. Upload them again."
419
+ available: ‹id›, ‹id›, ‹id›. Upload them again." New in 0.9.0: `code` is `"documents_missing"`,
420
+ `status` is 404, and `DocumentsNotFoundError.is(error)` tells one apart also when another copy of
421
+ the package made it (see [errors](./errors-and-retries.md#telling-errors-apart-across-copies-of-the-package)).
422
+
423
+ Since 0.9.0 `onMissingDocuments` can answer without them, or bring them back, instead.
350
424
 
351
425
  Guide: [errors and reliability](../guides/errors-and-reliability.md).
352
426
 
427
+ ### Missing documents
428
+
429
+ New in 0.9.0. `AskOptions.onMissingDocuments` says what a question does with documents of
430
+ `documentIds` that are missing. A document that expired (`ttlMs`), was deleted, was never stored,
431
+ or belongs to another owner or scope is missing: the four look the same, so another user's ID tells
432
+ nothing. It is settled before any model request.
433
+
434
+ - **`"throw"`** (the default): the question throws [`DocumentsNotFoundError`](#documentsnotfounderror),
435
+ as before.
436
+ - **`"drop"`**: the question is answered without them.
437
+ - The system instruction gets one line at its end: "1 of the attached files is no longer
438
+ available; say so if the question needs it." (or "3 of the attached files are no longer
439
+ available; say so if the question needs them."). Only in this question.
440
+ - `AskResult.missing` lists their IDs, and a `"documents_missing"` notice names them
441
+ (`documentIds`), before the `plan` event.
442
+ - With no document left, the question is a plain chat: no tool guide, no tools. The model may
443
+ then answer from what it knows, without saying the files are gone. To refuse instead, give a
444
+ function that throws when none is left:
445
+ `(missing) => (missing.length === new Set(documentIds).size ? "throw" : "drop")`, with the
446
+ question's own `documentIds`.
447
+ - **A function** gets the missing IDs and a [`MissingDocumentsContext`](#missingdocumentscontext),
448
+ and returns a [`MissingDocumentsAction`](#missingdocumentsaction), or a promise of one.
449
+ - `"throw"` or `"drop"`, as above.
450
+ - `{ retry: true }`: you ingested them again under the same IDs (`IngestInput.id`). The documents
451
+ are planned again, once.
452
+ - `{ replace: { [oldId]: newId } }`: you ingested them under new IDs. The documents are planned
453
+ again, once, with each new ID in the place of its old one.
454
+ - After a retry or a replace, an ID still missing fails the question with
455
+ `DocumentsNotFoundError`. When you cannot bring them all back, return `"drop"`: those you
456
+ ingested again are used from the next question.
457
+ - What it throws fails the question, as it came. When `signal` aborts while it runs, the
458
+ question ends at once with the signal's reason, whether the function looks at the signal or not.
459
+
460
+ A question planned again for a smaller window (after the provider refused its first request) keeps
461
+ what was settled: the function is not asked again about the same documents.
462
+
463
+ ```ts
464
+ import { askWithFiles, IngestError, type AskResult, type LargeFiles, type MissingDocumentsAction, type ModelAdapter } from "llm-large-files";
465
+
466
+ declare const files: LargeFiles;
467
+ declare const model: ModelAdapter;
468
+ // The uploads you keep, by their ID, which is also the document's ID.
469
+ declare const uploads: { find(userId: string, id: string): Promise<{ name: string; bytes: Uint8Array } | undefined> };
470
+
471
+ export async function ask(userId: string, chatId: string, documentIds: string[], question: string): Promise<AskResult> {
472
+ return askWithFiles({
473
+ files,
474
+ model,
475
+ owner: userId,
476
+ scope: [userId, chatId],
477
+ documentIds,
478
+ messages: [{ role: "user", text: question }],
479
+ // Ingest again what was kept; answer without the files that are gone for good.
480
+ onMissingDocuments: async (missing, { owner, scope }): Promise<MissingDocumentsAction> => {
481
+ let back = 0;
482
+ for (const id of missing) {
483
+ const upload = await uploads.find(userId, id);
484
+ if (!upload) continue;
485
+ try {
486
+ await files.ingest({ name: upload.name, bytes: upload.bytes, id, owner, scope });
487
+ } catch (error) {
488
+ // Another question of the chat ingested it meanwhile.
489
+ if (!(IngestError.is(error) && error.code === "exists")) throw error;
490
+ }
491
+ back++;
492
+ }
493
+ return back === missing.length ? { retry: true } : "drop";
494
+ },
495
+ });
496
+ }
497
+ ```
498
+
499
+ - Two questions of one chat can find the same document missing at once: a second tab, or a
500
+ question sent again. The second ingest gets an [`IngestError`](./library.md#ingesterror) of code
501
+ `"exists"`, and the ID counts as back. If the first has not stored it yet, that question fails
502
+ with `DocumentsNotFoundError`, and can be asked again.
503
+
504
+ ### `MissingDocumentsAction`
505
+
506
+ ```ts
507
+ type MissingDocumentsAction = "throw" | "drop" | { retry: true } | { replace: Record<string, string> };
508
+ ```
509
+
510
+ New in 0.9.0. What a function of `onMissingDocuments` returns: see
511
+ [missing documents](#missing-documents). Anything else is a `TypeError`: "onMissingDocuments returned
512
+ …: it must return "throw", "drop", { retry: true } or { replace: { [oldId]: newId } }." The map of
513
+ a replace is a plain object (made as `{}`, or with `Object.create(null)`), not a `Map` or an
514
+ instance of a class, and its new IDs are strings that are not empty. An action with a key of
515
+ another name, such as `{ retry: true, why: "…" }`, is a `TypeError` too.
516
+
517
+ ### `MissingDocumentsContext`
518
+
519
+ ```ts
520
+ type MissingDocumentsContext = { owner?: string; scope?: DocumentScope; signal?: AbortSignal };
521
+ ```
522
+
523
+ New in 0.9.0. What a function of `onMissingDocuments` is told besides the IDs: the `owner`, `scope`
524
+ and `signal` of the question, when it has them. Ingest again with the same owner and scope, or the
525
+ documents are still missing for the question.
526
+
527
+ ### `DEFAULT_INPUT_TOKENS`
528
+
529
+ ```ts
530
+ declare const DEFAULT_INPUT_TOKENS: 1_000_000;
531
+ ```
532
+
533
+ The least ceiling on the input tokens of a question that sets no `limits.inputTokens`. Its ceiling
534
+ is the larger of this and `toolTurns` times the estimate of its first request, with room for its
535
+ whole-file reads added (see [the default ceiling](#asklimits)). New in 0.10.0.
536
+
537
+ ### `ToolResultContext` and `ToolResultVerdict`
538
+
539
+ ```ts
540
+ type ToolResultContext = { call: ToolCall; result: ToolResult; documentId?: string; owner?: string; scope?: DocumentScope; signal: AbortSignal };
541
+ type ToolResultVerdict = { result: ToolResult } | { reject: string };
542
+ ```
543
+
544
+ What `AskOptions.onToolResult` is given, and what it returns. New in 0.10.0.
545
+
546
+ The hook is called once for each tool call that ran, as soon as its result is in, with the result
547
+ as the tool returned it. The hooks of one turn may run at the same time: an async check of 200 ms
548
+ adds about 200 ms to a turn of eight calls, not 1.6 s. Their verdicts are applied in call order, and
549
+ what they let through is then fitted to the room in the request, as the tool's own result would be:
550
+ a replacement larger than the room is cut, and keeps `redacted: true`. Nothing else sees a result
551
+ before its hook: the model, `evidence`, `steps`, `toolTurns`, `onStep` and the `tool.end` event all
552
+ get what the hook let through. A call refused by the loop (no room, a limit, an unknown tool,
553
+ arguments that did not arrive whole), answered with a pointer to an earlier result, or over
554
+ `callsPerTurn`, is not passed to it: the model gets no file text from those. The same call made
555
+ twice in one turn is passed once: the second gets the first one's verdict (the same replacement, or
556
+ the same error), and a pointer only when the hook kept the result. The question waits for an async
557
+ hook, and stops waiting when its signal aborts. A hook that fails ends the question at once, without
558
+ waiting for the hooks of the other calls.
559
+
560
+ | Field | Type | What it holds |
561
+ |---|---|---|
562
+ | `call` | [`ToolCall`](#toolcall) | The tool call, as the model made it. |
563
+ | `result` | [`ToolResult`](./tools.md#toolresult) | What the tool returned, before it is fitted to the room in the request. An error result (`{ error }`) is passed too. |
564
+ | `documentId` | `string`, optional | The document the call names (`args.document_id`), when it names one. |
565
+ | `owner` | `string`, optional | The question's `owner`. |
566
+ | `scope` | [`DocumentScope`](./library.md#documentscope), optional | The question's `scope`. |
567
+ | `signal` | `AbortSignal` | Aborts when the question is stopped or fails: pass it to a call of your own, such as a DLP service. |
568
+
569
+ | Verdict | What the model is sent | `tool.end` outcome |
570
+ |---|---|---|
571
+ | `{ result }` | That result in place of the tool's, with `redacted: true` added, fitted to the room in the request. A later call is never answered with a pointer to it ("already shown above"): it runs again, through the hook. The same call made again in the same turn gets the same replacement. | `"redacted"` |
572
+ | `{ reject: "why" }` | `{ error: "why" }`. No evidence. | `"refused"` |
573
+ | `undefined` | The tool's result. | as without the hook |
574
+
575
+ A verdict with a `result` key is a result, whatever else it holds: `{ result: { reject: "x" } }`
576
+ sends `{ reject: "x", redacted: true }`. A thrown error, a rejected promise, or a value of another
577
+ shape (`{ reject: 42 }`, `{ result: "text" }`, a result itself) ends the question with that error or
578
+ a `TypeError`: the hook is there to keep something from the model, and a mistake in it does not let
579
+ the result through.
580
+
581
+ ```ts
582
+ import { askWithFiles, type AskOptions, type AskResult, type ToolResult } from "llm-large-files";
583
+
584
+ const CARD = /(?<!\d)\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}(?!\d)/g;
585
+ /** Every string of a result with the card numbers in it masked; numbers and keys as they are. */
586
+ const masked = (value: unknown): unknown =>
587
+ typeof value === "string" ? value.replace(CARD, "[card]")
588
+ : Array.isArray(value) ? value.map(masked)
589
+ : value !== null && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([key, field]) => [key, masked(field)]))
590
+ : value;
591
+
592
+ // options are those of askWithFiles.
593
+ export function askMasked(options: AskOptions): Promise<AskResult> {
594
+ return askWithFiles({
595
+ ...options,
596
+ onToolResult: ({ result }) => {
597
+ const clean = masked(result) as ToolResult;
598
+ return JSON.stringify(clean) === JSON.stringify(result) ? undefined : { result: clean };
599
+ },
600
+ });
601
+ }
602
+ ```
603
+
604
+ ### `CitationCheck`
605
+
606
+ ```ts
607
+ type CitationCheck = { checked: number; supported: number; unchecked: number; unsupported: Array<{ document: string; line: number }> };
608
+
609
+ declare function checkCitations(text: string, evidence: Evidence[], names: Record<string, string>, formats?: Record<string, DocumentFormat>): CitationCheck;
610
+ ```
611
+
612
+ The line citations of an answer, checked against what the tools showed (`AskResult.citations`).
613
+ New in 0.10.0.
614
+
615
+ `checkCitations(text, evidence, names, formats?)` finds the citations of `text` and checks each
616
+ against `evidence`. `names` gives each document ID's file name; a document missing from it takes the
617
+ `document` of its evidence. `formats` gives each one's format, to tell a workbook's rows.
618
+
619
+ What it reads:
620
+
621
+ | Form | Example | Read as |
622
+ |---|---|---|
623
+ | `L` (or `l`, or `L` and a space) and a number or a range, with the file name next to it, in the same parentheses or on the same line | `(app.log L97)`, `(app.log L95-110, L118)`, `app.log L12–14`, `(L12 חוזה.docx)` | lines |
624
+ | `line` or `lines` and a number or a range | `app.log line 12`, `lines 12 to 14 of app.log` | lines |
625
+ | `Row` and a number | `sales.xlsx, Row 12` | a row: unchecked for a workbook (XLSX), a line for any other file |
626
+ | `שורה` and a number, `שורות` and a range, with a prefix letter or `מס'` | `לפי חוזה.docx, שורה 12`, `בשורות 40-45 של חשבוניות.csv`, `בשורה 40 בקובץ חשבוניות.csv` | as `Row`: in Hebrew שורה is both a line and a row |
627
+
628
+ A range is written with a hyphen, a dash, a maqaf (`12־14`), "to" or "עד". Hebrew points
629
+ (`שׁוּרָה`) and the marks that set the direction of text (RLM, LRM and the like) are not read.
630
+
631
+ A citation goes with the file name next to it: one in its parentheses, else one on its line within
632
+ 40 characters. A name after it that is introduced as its own ("line 40 of x", "בשורה 40 בקובץ x",
633
+ "שורה 40 בx") is its name: in "בשורה 12 בקובץ חוזה.docx, והאיחור בשורה 40 בקובץ חשבוניות.csv", line
634
+ 40 goes with חשבוניות.csv. Else, of the name before it and the name after it, the nearer one, where
635
+ a comma, a semicolon, the end of a sentence or "and" ("ו") between them counts as far, except a
636
+ comma or a colon right after the name before: in "לפי חוזה.docx, שורה 12 סותרת את חשבוניות.csv",
637
+ line 12 goes with חוזה.docx. The name may be
638
+ written without its extension ("report" for report.docx) or with a Hebrew prefix letter
639
+ ("בחוזה.docx"). With one file, a citation needs no name. A bare `L12` with no name next to it counts
640
+ only inside parentheses (`(L12)`): "the L2 cache" is no citation. A citation is supported when every
641
+ line it names was shown, by the lines of an evidence entry of that document. An entry with
642
+ `whole: true` (a file read whole, or sent whole) and no `lines` shows every line; one with `lines`
643
+ (`[[1, 120]]`) shows those, so a line past the end of the file is not supported. Two documents of
644
+ one name support it by either. `askWithFiles` counts each document sent whole, and each document
645
+ read whole (`analyze_whole_document`), as shown from its first line to its last
646
+ (`DocumentMeta.lines`): its `evidence` is not changed for that.
647
+
648
+ | Field | Type | What it holds |
649
+ |---|---|---|
650
+ | `checked` | `number` | Citations matched to a file and a line. |
651
+ | `supported` | `number` | Of those, the ones inside what the tools showed. A file sent whole counts as shown. |
652
+ | `unchecked` | `number` | Citations recognized but not matched: no file name when there are several files, or the row of a workbook. |
653
+ | `unsupported` | `Array<{ document: string; line: number }>` | The citations of lines the tools did not show. |
654
+
655
+ ### `AnswerInfo`
656
+
657
+ ```ts
658
+ type AnswerInfo = {
659
+ complete: boolean;
660
+ reason?: "filtered" | "cut" | "blocked" | "language" | "no_answer" | "other";
661
+ finish?: AskResult["finish"];
662
+ finishReason?: string;
663
+ };
664
+
665
+ declare function answerInfoOf(result: Pick<AskResult, "answered" | "finish" | "finishReason" | "blockReason">): AnswerInfo;
666
+ ```
667
+
668
+ How an answer ended, in one value to switch on for the message an application shows: the
669
+ answer's counterpart of [`errorInfoOf`](./errors-and-retries.md). New in 0.10.0.
670
+
671
+ `answerInfoOf(result)` tries the reasons in this order: a refused prompt (`blockReason`:
672
+ `"blocked"`), a filter (`finish` `"filtered"`), the output limit (`"cut"`), Gemini's `LANGUAGE`
673
+ (`finishReason` `"LANGUAGE"` with any `finish` but `"complete"`: `"language"`, which is not a
674
+ filter), another reason that asking again does not mend (`"other"`), and no text (`answered`
675
+ false: `"no_answer"`). Otherwise the answer is complete. It reads only these four fields, so a result
676
+ kept from an earlier version, or built by hand, works too. The messages to show, in Hebrew and
677
+ English: [errors and reliability](../guides/errors-and-reliability.md#filtered-and-cut-answers).
678
+
679
+ | Field | Type | What it holds |
680
+ |---|---|---|
681
+ | `complete` | `boolean` | True when the answer came whole: not stopped by a filter or the output limit, and not refused. |
682
+ | `reason` | `"filtered" \| "cut" \| "blocked" \| "language" \| "no_answer" \| "other"`, optional | Why it is not complete. `"language"`: Gemini's `LANGUAGE`, a language the model does not take. |
683
+ | `finish` | `AskResult["finish"]`, optional | `AskResult.finish`. |
684
+ | `finishReason` | `string`, optional | The provider's own word (`AskResult.finishReason`). |
685
+
353
686
  ## What the loop adds to its requests
354
687
 
355
688
  Each is a `string`. The loop adds them itself. They are exported so that you can recognise them in
@@ -374,6 +707,14 @@ and tool calls were answered:
374
707
  > Stop using tools now. Answer my question using only what the tools returned above, with line
375
708
  > citations. Say plainly what you could not find. Answer in the language of my question.
376
709
 
710
+ When files were also sent whole, with their lines numbered or tables the tools count
711
+ (`numberInline`, `inlineTables`), the line says to answer from them too (new in 0.10.0; it is not
712
+ exported):
713
+
714
+ > Stop using tools now. Answer my question using only the files shown in full and what the tools
715
+ > returned above, with line citations. Say plainly what you could not find. Answer in the language
716
+ > of my question.
717
+
377
718
  ### `FINAL_ANSWER_AFTER_PAGES`
378
719
 
379
720
  The same, when every document went in whole and the only tool was `view_pages`:
@@ -390,11 +731,11 @@ was empty, or no turn was left for tools), so there is no tool result to answer
390
731
  > if the answer needs a part of a file that is not shown here, say so plainly. Answer in the language
391
732
  > of my question.
392
733
 
393
- The three end with "Answer in the language of my question." since 0.8.0: a model asked in Hebrew
734
+ They all end with "Answer in the language of my question." since 0.8.0: a model asked in Hebrew
394
735
  answered in English after an English closing request. To have answers in one language whatever
395
736
  the question, say so in `system`.
396
737
 
397
- None of the three is kept in the conversation or in `toolTurns`. Nor is the note of the answer's
738
+ None of them is kept in the conversation or in `toolTurns`. Nor is the note of the answer's
398
739
  second try, which is not exported (new in 0.6.0): "Your last reply had no text. No tool can be
399
740
  called in this reply: write the answer now, in text, from what is above."
400
741
 
@@ -440,7 +781,9 @@ A plain turn of the user or of the model. `"model"` is taken as `"assistant"`.
440
781
  ### `ToolTurn`
441
782
 
442
783
  ```ts
443
- type ToolTurn = { role: "tools"; calls: Array<ToolCall & { result: ToolResult }> };
784
+ type ToolTurn = { role: "tools"; version?: number; calls: Array<ToolCall & { result: ToolResult }> };
785
+
786
+ declare const TOOL_TURN_VERSION: 1;
444
787
  ```
445
788
 
446
789
  One round of tool use as an application stores it: the calls of one model turn, each with what the
@@ -455,6 +798,13 @@ regex search that 0.5.0 stored without its last match: those run again (see
455
798
  [tools](./tools.md#what-askwithfiles-adds-to-results)). Guide:
456
799
  [conversations](../guides/conversations.md).
457
800
 
801
+ `version` is the version of this shape, new in 0.9.0: `TOOL_TURN_VERSION` (1) on the rounds
802
+ `askWithFiles` returns, absent on those of earlier versions, which are read as before. It is never
803
+ sent to the model: of a stored round, only its calls are. A round of a higher version, made by a
804
+ newer version of the package, is refused with a `TypeError` ("A stored tool round (toolTurns) has
805
+ version 2: …"), before any request. Catch it to ask again without the old rounds. A test that
806
+ compares the rounds whole must expect `version`.
807
+
458
808
  ## The adapter contract
459
809
 
460
810
  An adapter turns the loop's neutral request into a provider's, sends it, and reads the reply back.
@@ -616,7 +966,8 @@ type ModelPart = { text: string; native?: undefined } | { native: unknown; text?
616
966
 
617
967
  One piece of a message: plain text, or something in the provider's own form (an image, an inline
618
968
  PDF) that only its adapter reads. A native part may carry the text it holds in `text`: the loop
619
- then sizes it by that text; otherwise by the size of its JSON. Each built-in adapter passes a native
969
+ then counts its tokens from that text, and its bytes from the larger of the text and the part's
970
+ JSON (since 0.9.0; before, from the text alone); otherwise it sizes it by the size of its JSON. Each built-in adapter passes a native
620
971
  part on to its provider as it is, and the loop sends it to every model of the question, so with an
621
972
  explorer of another provider, that model gets it too.
622
973
 
@@ -665,8 +1016,10 @@ type ModelReply = {
665
1016
  calls: ToolCall[];
666
1017
  raw?: unknown;
667
1018
  finishReason?: string;
668
- finish?: "complete" | "cut" | "filtered" | "malformed_call";
1019
+ finish?: "complete" | "cut" | "filtered" | "malformed_call" | "other"; // "other": new in 0.10.0
669
1020
  blockReason?: string;
1021
+ responseId?: string; // new in 0.10.0
1022
+ responseModel?: string; // new in 0.10.0
670
1023
  usage?: Partial<ModelUsage>;
671
1024
  providerUsage?: Record<string, unknown>;
672
1025
  };
@@ -678,8 +1031,10 @@ type ModelReply = {
678
1031
  | `calls` | The tool calls of this reply, in order. `[]` when there are none. |
679
1032
  | `raw` | This turn in the provider's own form, to be sent back unchanged with the tool results. The loop gives it back only to this adapter. |
680
1033
  | `finishReason` | Why the reply ended, in the provider's own word (`"STOP"`, `"length"`, `"end_turn"`). It becomes `result.finishReason`. |
681
- | `finish` | How the reply ended, in terms every adapter maps its own to: `"complete"`; `"cut"` at the output limit; `"filtered"` by the provider's safety filters; `"malformed_call"`, a tool call the model tried to make that could not be read (Gemini's `MALFORMED_FUNCTION_CALL`). Unset when the adapter does not know. The loop asks once more, with a note, after a reply with no calls that is `"malformed_call"`, or that is empty before any tool ran and is neither `"cut"` nor `"filtered"`, while a tool turn is left before the answer. It also asks once more for the answer when its reply has no text and is not `"filtered"`: empty and not `"cut"`, or with calls, or `"malformed_call"`. At most two such second tries a question, the answer's included, and none for a reply with `blockReason` or once `limits.inputTokens` or `limits.requests` is reached. |
1034
+ | `finish` | How the reply ended, in terms every adapter maps its own to: `"complete"`; `"cut"` at the output limit; `"filtered"` by the provider's safety filters; `"malformed_call"`, a tool call the model tried to make that could not be read (Gemini's `MALFORMED_FUNCTION_CALL`); `"other"`, a known reason that is none of these and that asking again does not mend (new in 0.10.0: `gemini()` gives it for Gemini's `OTHER`, `LANGUAGE`, `FINISH_REASON_UNSPECIFIED`, `NO_IMAGE`, `TOO_MANY_TOOL_CALLS` and `MISSING_THOUGHT_SIGNATURE`). Unset when the adapter does not know. The loop asks once more, with a note, after a reply with no calls that is `"malformed_call"`, or that is empty before any tool ran and is none of `"cut"`, `"filtered"` and `"other"`, while a tool turn is left before the answer. It also asks once more for the answer when its reply has no text and is neither `"filtered"` nor `"other"`: empty and not `"cut"`, or with calls, or `"malformed_call"`. At most two such second tries a question, the answer's included, and none for a reply with `blockReason` or once `limits.requests` or the ceiling of input tokens is reached. A reply `"malformed_call"` with text is not the answer (since 0.10.0). It becomes `result.finish` when it is the last reply. |
682
1035
  | `blockReason` | Why the provider refused the prompt, when it did. A reply with `blockReason` and no calls ends the question: no request for the answer follows, and the result has `answered: false` and this `blockReason`. |
1036
+ | `responseId` | The provider's ID of this response (Gemini's `responseId`, the `id` of OpenAI and Claude), when it gives one. `gemini()`, `openAiCompatible()` and `anthropic()` set it. New in 0.10.0. |
1037
+ | `responseModel` | The model that wrote this response, as the provider names it (Gemini's `modelVersion`, the `model` of OpenAI and Claude). `gemini()`, `openAiCompatible()` and `anthropic()` set it. New in 0.10.0. |
683
1038
  | `usage` | The tokens of this request ([`ModelUsage`](#modelusage)), as far as the provider says. `inputTokens` must count every token of the prompt, cached ones included, and `outputTokens` the thoughts. The loop adds it to `result.usage`, and uses `inputTokens` to correct its own estimate of the request's size. |
684
1039
  | `providerUsage` | The provider's own usage object, as it came. It becomes `result.lastUsage`. |
685
1040
 
@@ -750,6 +1105,8 @@ Tokens of one request, or summed over several.
750
1105
  type UsageTotals = ModelUsage & {
751
1106
  requests: number;
752
1107
  byModel: Record<string, ModelUsage & { requests: number }>;
1108
+ estimatedInputTokens?: number; // new in 0.10.0
1109
+ unmeasuredRequests?: number; // new in 0.10.0
753
1110
  };
754
1111
  ```
755
1112
 
@@ -761,6 +1118,8 @@ in all and by model.
761
1118
  | `inputTokens`, `cachedInputTokens`, `outputTokens`, `thoughtTokens` | The sums over every request, as in [`ModelUsage`](#modelusage). |
762
1119
  | `requests` | Requests that were answered. One that failed and was sent again counts once; one that failed in the end does not count. |
763
1120
  | `byModel` | The same totals for each model, keyed by the adapter's `id`. |
1121
+ | `estimatedInputTokens` | Optional. The input tokens of the requests whose provider did not give them (no usage, or an input of 0), by the library's estimate, in each model's own tokens (`tokenScale`): the chat requests as the loop sized them, and the part reads of a whole-file read by their system text and prompt. The ceiling of the question counts them with `inputTokens`. They are not in `inputTokens` nor in `byModel`. Absent when every request gave its input. New in 0.10.0. |
1122
+ | `unmeasuredRequests` | Optional. The requests counted in `estimatedInputTokens`. Absent when there was none. New in 0.10.0. |
764
1123
 
765
1124
  Guide: [costs and limits](../guides/costs-and-limits.md).
766
1125
 
@@ -769,14 +1128,17 @@ Guide: [costs and limits](../guides/costs-and-limits.md).
769
1128
  ```ts
770
1129
  declare class UsageMeter {
771
1130
  readonly totals: UsageTotals;
772
- add(model: string, usage: Partial<ModelUsage> | undefined): void;
1131
+ add(model: string, usage: Partial<ModelUsage> | undefined, estimatedInputTokens?: number): void;
773
1132
  }
774
1133
  ```
775
1134
 
776
1135
  Sums the usage of the requests of one question: `askWithFiles` uses one, and you can use one in a
777
1136
  loop of your own. `totals` starts at zero, with an empty `byModel`. `add` counts one request in
778
1137
  `totals` and in `totals.byModel[model]`, and adds each field of `usage` that is a finite number
779
- above 0. With `usage` undefined it counts the request and no tokens.
1138
+ above 0. With `usage` undefined it counts the request and no tokens. New in 0.10.0: with
1139
+ `estimatedInputTokens`, your estimate of the request's input in the model's tokens, a request whose
1140
+ `usage` does not give its input (none, or 0) adds the estimate to `totals.estimatedInputTokens`, and
1141
+ counts in `totals.unmeasuredRequests`. Without it, such a request is counted as before.
780
1142
 
781
1143
  ```ts
782
1144
  import { UsageMeter } from "llm-large-files";
@@ -811,20 +1173,22 @@ type Evidence = {
811
1173
  ```
812
1174
 
813
1175
  What one tool call showed the model of one document: `result.evidence` holds one for each call
814
- that showed something.
1176
+ that showed something. Since 0.10.0 `askWithFiles` lists before them one entry for each file sent
1177
+ whole, in the order of its block: `{ tool: "inline", documentId, document, lines: [[1, n]], whole:
1178
+ true }`, with no `callId`, since no tool call showed it.
815
1179
 
816
1180
  | Field | What it holds |
817
1181
  |---|---|
818
- | `tool` | The tool that was called: `"search_document"`, `"read_document"`, `"get_document_overview"`, `"analyze_whole_document"`, `"view_pages"`. |
1182
+ | `tool` | The tool that was called: `"search_document"`, `"read_document"`, `"get_document_overview"`, `"aggregate_table"`, `"analyze_whole_document"`, `"view_pages"`. Or `"inline"`: a file sent whole, every line of which was in the prompt (since 0.10.0). |
819
1183
  | `documentId` | The document's ID. |
820
1184
  | `document` | The file's name, when the result gave it. |
821
- | `lines` | The lines the model was shown, merged and in order. A read: its lines. A search: its passages, or each matching line with the lines of context around it, the last matching line of the file included when the search showed it. An overview: the first 30 and the last 20 lines (all of them in a file of 30 lines or fewer). |
1185
+ | `lines` | The lines the model was shown, merged and in order. A read: its lines. A search: its passages, or each matching line with the lines of context around it, the last matching line of the file included when the search showed it. An overview: the first 30 and the last 20 lines (all of them in a file of 30 lines or fewer). An `aggregate_table` call: its header line and the lines its groups list (the table's other rows were counted, not shown). A whole-file read with `output: "items"`: the line of each item (since 0.10.0). |
822
1186
  | `pages` | The pages it looked at (`view_pages`), or the pages those lines are on, where the tool said. |
823
1187
  | `query` | What was searched for, or the task of a whole-file read. |
824
1188
  | `mode` | `"keywords"`, `"exact"` or `"regex"`, for a search. |
825
1189
  | `totalMatchingLines` | For an exact or regex search: how many lines match in the whole file, often more than were shown. |
826
- | `whole` | True for a whole-file read: other model requests read every line, and the model saw their answer. It has no `lines`. |
827
- | `callId` | The tool call it came from, as its events name it (`"call_3"`): the `callId` of its `tool.start` and `tool.end`, whose `evidence` is this entry. `askWithFiles` always sets it; [`evidenceOf`](#evidenceofcall-result) does not. New in 0.7.0. |
1190
+ | `whole` | True for a whole-file read: other model requests read every line, and the model saw their answer. It has no `lines`, except the lines of its items with `output: "items"`. True too for a file sent whole (`tool: "inline"`), whose `lines` are all of its lines, `[[1, n]]`. |
1191
+ | `callId` | The tool call it came from, as its events name it (`"call_3"`): the `callId` of its `tool.start` and `tool.end`, whose `evidence` is this entry. `askWithFiles` sets it on every entry but those of the files sent whole (`tool: "inline"`), which no tool call showed: code that matches evidence to `tool.end` skips entries without it. [`evidenceOf`](#evidenceofcall-result) does not set it. New in 0.7.0. |
828
1192
 
829
1193
  ```ts
830
1194
  import { mergeRanges, type AskResult, type NumberRange } from "llm-large-files";
@@ -897,12 +1261,16 @@ older tool results, and for the pages in `result.toolTurns`. Set `hadFiles` (def
897
1261
  result whose files (pages) are dropped with it, however small its JSON is.
898
1262
 
899
1263
  It returns `undefined` when there is nothing to gain: the result is an error, is already a
900
- stand-in, or (without `hadFiles`) its JSON is under 700 characters. Otherwise, by tool:
1264
+ stand-in, or (without `hadFiles`) its JSON is under 700 characters, or is no larger than its
1265
+ stand-in would be. That last rule is new in 0.9.0: a search counted by group, or an
1266
+ `aggregate_table` result, of a few short groups came out larger as a stand-in (845 characters grew
1267
+ to 1,073), and replaced the result it was meant to shorten. Otherwise, by tool:
901
1268
 
902
1269
  | Tool | The stand-in keeps |
903
1270
  |---|---|
904
1271
  | `read_document` | `lines`, `total_lines` |
905
- | `search_document` | `mode`, `query` (its first 200 characters), `total_matching_lines`, `lines_shown` (up to 60 ranges, such as `"120-180"`, the last match's among them when the search showed it) |
1272
+ | `search_document` | `mode`, `query` (its first 200 characters), `total_matching_lines`, `lines_shown` (up to 60 ranges, such as `"120-180"`, the last match's among them when the search showed it); with `group_by`, `group_by`, `total_groups` and the first 30 `groups` |
1273
+ | `aggregate_table` | `table`, `rows_matched`, `total_groups`, and the first 30 `groups` |
906
1274
  | `analyze_whole_document` | `parts_read`, and the first 6,000 characters of `answer`, followed by "…" when it was longer: the answer cannot be asked for again |
907
1275
  | `view_pages` | `pages`, `total_pages` |
908
1276
  | `get_document_overview`, any other | nothing more than `document` and the note |