llm-large-files 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/CHANGELOG.md +446 -0
  2. package/README.md +13 -7
  3. package/dist/access.d.ts +45 -3
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +106 -3
  6. package/dist/access.js.map +1 -1
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +115 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +572 -103
  26. package/dist/ask.js.map +1 -1
  27. package/dist/citations.d.ts +36 -0
  28. package/dist/citations.d.ts.map +1 -0
  29. package/dist/citations.js +291 -0
  30. package/dist/citations.js.map +1 -0
  31. package/dist/error-info.d.ts +13 -0
  32. package/dist/error-info.d.ts.map +1 -1
  33. package/dist/error-info.js +37 -1
  34. package/dist/error-info.js.map +1 -1
  35. package/dist/errors.d.ts +3 -1
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +3 -1
  38. package/dist/errors.js.map +1 -1
  39. package/dist/events.d.ts +25 -7
  40. package/dist/events.d.ts.map +1 -1
  41. package/dist/events.js.map +1 -1
  42. package/dist/evidence.d.ts.map +1 -1
  43. package/dist/evidence.js +21 -2
  44. package/dist/evidence.js.map +1 -1
  45. package/dist/extract.d.ts.map +1 -1
  46. package/dist/extract.js +6 -1
  47. package/dist/extract.js.map +1 -1
  48. package/dist/gemini/adapter.d.ts +35 -4
  49. package/dist/gemini/adapter.d.ts.map +1 -1
  50. package/dist/gemini/adapter.js +68 -29
  51. package/dist/gemini/adapter.js.map +1 -1
  52. package/dist/gemini/chat.d.ts +28 -55
  53. package/dist/gemini/chat.d.ts.map +1 -1
  54. package/dist/gemini/chat.js +20 -27
  55. package/dist/gemini/chat.js.map +1 -1
  56. package/dist/gemini/endpoints.d.ts +59 -11
  57. package/dist/gemini/endpoints.d.ts.map +1 -1
  58. package/dist/gemini/endpoints.js +33 -7
  59. package/dist/gemini/endpoints.js.map +1 -1
  60. package/dist/gemini/errors.d.ts +39 -5
  61. package/dist/gemini/errors.d.ts.map +1 -1
  62. package/dist/gemini/errors.js +70 -9
  63. package/dist/gemini/errors.js.map +1 -1
  64. package/dist/gemini/generate.d.ts +53 -2
  65. package/dist/gemini/generate.d.ts.map +1 -1
  66. package/dist/gemini/generate.js +100 -50
  67. package/dist/gemini/generate.js.map +1 -1
  68. package/dist/gemini/index.d.ts +3 -3
  69. package/dist/gemini/index.d.ts.map +1 -1
  70. package/dist/http.d.ts +41 -3
  71. package/dist/http.d.ts.map +1 -1
  72. package/dist/http.js +40 -2
  73. package/dist/http.js.map +1 -1
  74. package/dist/index.d.ts +6 -4
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ingest.d.ts +9 -1
  79. package/dist/ingest.d.ts.map +1 -1
  80. package/dist/ingest.js +50 -25
  81. package/dist/ingest.js.map +1 -1
  82. package/dist/library.d.ts +129 -2
  83. package/dist/library.d.ts.map +1 -1
  84. package/dist/library.js +224 -149
  85. package/dist/library.js.map +1 -1
  86. package/dist/map-reduce.d.ts +176 -10
  87. package/dist/map-reduce.d.ts.map +1 -1
  88. package/dist/map-reduce.js +804 -58
  89. package/dist/map-reduce.js.map +1 -1
  90. package/dist/model.d.ts +36 -4
  91. package/dist/model.d.ts.map +1 -1
  92. package/dist/model.js +17 -1
  93. package/dist/model.js.map +1 -1
  94. package/dist/node/handlers.d.ts +29 -8
  95. package/dist/node/handlers.d.ts.map +1 -1
  96. package/dist/node/handlers.js +148 -126
  97. package/dist/node/handlers.js.map +1 -1
  98. package/dist/node/index.d.ts +1 -1
  99. package/dist/node/index.d.ts.map +1 -1
  100. package/dist/node/index.js.map +1 -1
  101. package/dist/node/ingest-child.js +2 -2
  102. package/dist/node/ingest-child.js.map +1 -1
  103. package/dist/node/spool.d.ts +9 -5
  104. package/dist/node/spool.d.ts.map +1 -1
  105. package/dist/node/spool.js +28 -15
  106. package/dist/node/spool.js.map +1 -1
  107. package/dist/node/sse.d.ts +6 -5
  108. package/dist/node/sse.d.ts.map +1 -1
  109. package/dist/node/sse.js +8 -7
  110. package/dist/node/sse.js.map +1 -1
  111. package/dist/openai/adapter.d.ts +5 -1
  112. package/dist/openai/adapter.d.ts.map +1 -1
  113. package/dist/openai/adapter.js +53 -12
  114. package/dist/openai/adapter.js.map +1 -1
  115. package/dist/output-limit.d.ts +2 -1
  116. package/dist/output-limit.d.ts.map +1 -1
  117. package/dist/output-limit.js +5 -2
  118. package/dist/output-limit.js.map +1 -1
  119. package/dist/pdf-outline.d.ts +71 -0
  120. package/dist/pdf-outline.d.ts.map +1 -0
  121. package/dist/pdf-outline.js +414 -0
  122. package/dist/pdf-outline.js.map +1 -0
  123. package/dist/plan.d.ts +137 -7
  124. package/dist/plan.d.ts.map +1 -1
  125. package/dist/plan.js +248 -26
  126. package/dist/plan.js.map +1 -1
  127. package/dist/prepare.d.ts +50 -0
  128. package/dist/prepare.d.ts.map +1 -0
  129. package/dist/prepare.js +207 -0
  130. package/dist/prepare.js.map +1 -0
  131. package/dist/ranged.d.ts +2 -1
  132. package/dist/ranged.d.ts.map +1 -1
  133. package/dist/ranged.js +16 -3
  134. package/dist/ranged.js.map +1 -1
  135. package/dist/search.d.ts +7 -0
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +72 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/stores.d.ts +6 -0
  140. package/dist/stores.d.ts.map +1 -1
  141. package/dist/stores.js +82 -11
  142. package/dist/stores.js.map +1 -1
  143. package/dist/tools.d.ts +22 -2
  144. package/dist/tools.d.ts.map +1 -1
  145. package/dist/tools.js +323 -76
  146. package/dist/tools.js.map +1 -1
  147. package/dist/types.d.ts +49 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/whole-cost.d.ts +37 -0
  150. package/dist/whole-cost.d.ts.map +1 -0
  151. package/dist/whole-cost.js +46 -0
  152. package/dist/whole-cost.js.map +1 -0
  153. package/docs/README.md +4 -0
  154. package/docs/guides/anthropic.md +5 -2
  155. package/docs/guides/conversations.md +1 -1
  156. package/docs/guides/costs-and-limits.md +132 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +157 -45
  159. package/docs/guides/explorer-model.md +4 -1
  160. package/docs/guides/openai-compatible.md +47 -7
  161. package/docs/guides/own-adapter-and-loop.md +33 -6
  162. package/docs/guides/pdfs.md +96 -7
  163. package/docs/guides/storage.md +46 -3
  164. package/docs/guides/testing.md +71 -0
  165. package/docs/guides/vertex-and-gemini.md +159 -50
  166. package/docs/guides/web-app.md +10 -6
  167. package/docs/how-it-works.md +120 -22
  168. package/docs/measurements.md +172 -5
  169. package/docs/publishing.md +76 -4
  170. package/docs/reference/anthropic.md +12 -7
  171. package/docs/reference/ask.md +262 -35
  172. package/docs/reference/errors-and-retries.md +30 -2
  173. package/docs/reference/events.md +27 -10
  174. package/docs/reference/gemini.md +184 -68
  175. package/docs/reference/library.md +190 -23
  176. package/docs/reference/node.md +51 -17
  177. package/docs/reference/openai.md +21 -10
  178. package/docs/reference/tools.md +271 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +472 -0
  182. package/package.json +5 -1
  183. package/src/access.ts +127 -4
  184. package/src/aggregate.ts +92 -14
  185. package/src/analyze.ts +2 -2
  186. package/src/answer-info.ts +45 -0
  187. package/src/anthropic/adapter.ts +40 -11
  188. package/src/ask.ts +646 -106
  189. package/src/citations.ts +294 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +29 -6
  193. package/src/evidence.ts +21 -2
  194. package/src/extract.ts +6 -1
  195. package/src/gemini/adapter.ts +99 -32
  196. package/src/gemini/chat.ts +53 -82
  197. package/src/gemini/endpoints.ts +89 -16
  198. package/src/gemini/errors.ts +74 -11
  199. package/src/gemini/generate.ts +147 -57
  200. package/src/gemini/index.ts +3 -3
  201. package/src/http.ts +65 -4
  202. package/src/index.ts +6 -4
  203. package/src/ingest.ts +58 -27
  204. package/src/library.ts +336 -142
  205. package/src/map-reduce.ts +855 -67
  206. package/src/model.ts +44 -4
  207. package/src/node/handlers.ts +159 -118
  208. package/src/node/index.ts +1 -0
  209. package/src/node/ingest-child.ts +2 -2
  210. package/src/node/spool.ts +28 -14
  211. package/src/node/sse.ts +8 -7
  212. package/src/openai/adapter.ts +56 -13
  213. package/src/output-limit.ts +5 -2
  214. package/src/pdf-outline.ts +400 -0
  215. package/src/plan.ts +287 -36
  216. package/src/prepare.ts +253 -0
  217. package/src/ranged.ts +16 -3
  218. package/src/search.ts +69 -13
  219. package/src/stores.ts +76 -11
  220. package/src/tools.ts +327 -75
  221. package/src/types.ts +45 -1
  222. package/src/whole-cost.ts +64 -0
@@ -9,11 +9,12 @@ task, where there is one.
9
9
  ```ts
10
10
  import {
11
11
  askWithFiles, askStream, partialResultOf, DocumentsNotFoundError, UsageMeter, TOOL_TURN_VERSION,
12
- evidenceOf, mergeRanges, stubResult,
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
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,
@@ -32,7 +33,10 @@ Contents:
32
33
  [`partialResultOf(error)`](#partialresultoferror),
33
34
  [`DocumentsNotFoundError`](#documentsnotfounderror), [missing documents](#missing-documents),
34
35
  [`MissingDocumentsAction`](#missingdocumentsaction),
35
- [`MissingDocumentsContext`](#missingdocumentscontext)
36
+ [`MissingDocumentsContext`](#missingdocumentscontext),
37
+ [`DEFAULT_INPUT_TOKENS`](#default_input_tokens),
38
+ [`ToolResultContext` and `ToolResultVerdict`](#toolresultcontext-and-toolresultverdict),
39
+ [`CitationCheck`](#citationcheck), [`AnswerInfo`](#answerinfo)
36
40
  - **What the loop adds to its requests:** [`EXPLORER_INSTRUCTION`](#explorer_instruction),
37
41
  [`FINAL_ANSWER_REQUEST`](#final_answer_request),
38
42
  [`FINAL_ANSWER_AFTER_PAGES`](#final_answer_after_pages),
@@ -81,22 +85,48 @@ What it does, in order:
81
85
  2. **Plans the documents** with `files.prepare`, for the room the conversation leaves. Documents
82
86
  that are missing are settled by `onMissingDocuments` before any model request: by default the
83
87
  question throws `DocumentsNotFoundError` ([missing documents](#missing-documents)).
84
- 3. **Sends one request without tools** to `model` when every document went in whole and no PDF
85
- can be looked at, and returns its reply.
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).
86
93
  4. **Otherwise runs tool rounds.** The model that explores (`explorer`, or `model` without one)
87
- gets the tools. Of each turn's calls, the loop runs at most `limits.callsPerTurn`, up to four
88
- at a time, each result fitted to the room left in the request, and sends the results back.
89
- 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.
90
100
  5. **Ends with the answer.** A reply with text and no tool call is the answer, when there is no
91
- explorer. Otherwise (out of turns, room or `limits`, a reply with no text, an explorer that is
92
- done) `model` gets one more request: the tools listed, `toolChoice: "none"`, and one of the
93
- [`FINAL_ANSWER_*`](#final_answer_request) lines as a user turn at the end. When its reply has
94
- no text (it is empty, or holds a tool call the model was told not to make), that request is
95
- sent once more with a note after the line, which is not kept: "Your last reply had no text. No
96
- tool can be called in this reply: write the answer now, in text, from what is above." Not after
97
- a refusal (`blockReason`), a reply `"filtered"`, or one `"cut"` with nothing in it; not once
98
- `limits.requests` or `limits.inputTokens` is reached; and not when the question already made its
99
- 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.
100
130
 
101
131
  A request that fails is sent again by the rule of `retry` (see
102
132
  [`withRetry`](./errors-and-retries.md#withretryrun-options)), but never once text of its reply was
@@ -129,6 +159,8 @@ planned again shortens them again without saying so twice.
129
159
  | `Error`: "The last message must be the user's." | `messages` is empty, or its last message is not a user turn. | undefined |
130
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 |
131
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 |
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 |
132
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 |
133
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 |
134
166
  | What the function of `onMissingDocuments` threw | It threw, or its promise rejected. Before any request. New in 0.9.0. | undefined |
@@ -137,7 +169,7 @@ planned again shortens them again without saying so twice.
137
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 |
138
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 |
139
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 |
140
- | 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)) |
141
173
 
142
174
  When the documents were planned again after an overflow and the second plan fails before it sends
143
175
  anything, the first overflow error is thrown, with what the first try had done. A whole-file part
@@ -246,7 +278,7 @@ The options of `askWithFiles`.
246
278
  |---|---|---|---|
247
279
  | `files` | [`LargeFiles`](./library.md#largefiles) | required | The library that holds the documents, plans them and makes the tools. |
248
280
  | `model` | [`ModelAdapter`](#modeladapter) | required | The model that answers. Without `explorer`, it also makes the tool calls and reads whole files in parts. |
249
- | `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. |
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). |
250
282
  | `documentIds` | `string[]` | required | The documents this question may use. Duplicates count once. One that is missing throws [`DocumentsNotFoundError`](#documentsnotfounderror), unless `onMissingDocuments` says otherwise. |
251
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. |
252
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. |
@@ -259,6 +291,8 @@ The options of `askWithFiles`.
259
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. |
260
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. |
261
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. |
262
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. |
263
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. |
264
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. |
@@ -266,7 +300,9 @@ The options of `askWithFiles`.
266
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. |
267
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. |
268
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. |
269
- | `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. |
270
306
 
271
307
  Guides: [conversations](../guides/conversations.md) (`messages`, `documentPlacement`),
272
308
  [storage](../guides/storage.md) (`owner`), [web app](../guides/web-app.md) (`onText`,
@@ -284,11 +320,20 @@ every tool. `Infinity` sets no ceiling.
284
320
 
285
321
  | Field | Type | Default | What it does |
286
322
  |---|---|---|---|
287
- | `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. |
288
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. |
289
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`. |
290
- | `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. |
291
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.
292
337
 
293
338
  `askGemini` also takes `maxToolTurns` and `maxToolCallsPerTurn`, the names these had before 0.5.0
294
339
  (see [gemini](./gemini.md)). Guide: [costs and limits](../guides/costs-and-limits.md).
@@ -301,18 +346,20 @@ question that failed.
301
346
  | Field | Type | What it holds |
302
347
  |---|---|---|
303
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. |
304
- | `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). |
305
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. |
306
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. |
307
- | `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). |
308
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. |
309
354
  | `plan` | [`DocumentPlan`](./library.md#documentplan) | Which documents went in whole (`inline`) and which were reached through tools (`searchable`). |
310
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. |
311
356
  | `budget` | [`Budget`](./library.md#budget) | The budget the question ran with: the library's (with `options.budget`), fitted to the models. |
312
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. |
313
358
  | `finishReason` | `string`, optional | The provider's own word for why the last reply that gave one ended (`"STOP"`, `"length"`, `"end_turn"`). |
314
- | `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`. |
315
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. |
316
363
 
317
364
  Guides: [conversations](../guides/conversations.md) (`toolTurns`),
318
365
  [costs and limits](../guides/costs-and-limits.md) (`usage`),
@@ -477,6 +524,165 @@ New in 0.9.0. What a function of `onMissingDocuments` is told besides the IDs: t
477
524
  and `signal` of the question, when it has them. Ingest again with the same owner and scope, or the
478
525
  documents are still missing for the question.
479
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
+
480
686
  ## What the loop adds to its requests
481
687
 
482
688
  Each is a `string`. The loop adds them itself. They are exported so that you can recognise them in
@@ -501,6 +707,14 @@ and tool calls were answered:
501
707
  > Stop using tools now. Answer my question using only what the tools returned above, with line
502
708
  > citations. Say plainly what you could not find. Answer in the language of my question.
503
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
+
504
718
  ### `FINAL_ANSWER_AFTER_PAGES`
505
719
 
506
720
  The same, when every document went in whole and the only tool was `view_pages`:
@@ -517,11 +731,11 @@ was empty, or no turn was left for tools), so there is no tool result to answer
517
731
  > if the answer needs a part of a file that is not shown here, say so plainly. Answer in the language
518
732
  > of my question.
519
733
 
520
- 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
521
735
  answered in English after an English closing request. To have answers in one language whatever
522
736
  the question, say so in `system`.
523
737
 
524
- 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
525
739
  second try, which is not exported (new in 0.6.0): "Your last reply had no text. No tool can be
526
740
  called in this reply: write the answer now, in text, from what is above."
527
741
 
@@ -802,8 +1016,10 @@ type ModelReply = {
802
1016
  calls: ToolCall[];
803
1017
  raw?: unknown;
804
1018
  finishReason?: string;
805
- finish?: "complete" | "cut" | "filtered" | "malformed_call";
1019
+ finish?: "complete" | "cut" | "filtered" | "malformed_call" | "other"; // "other": new in 0.10.0
806
1020
  blockReason?: string;
1021
+ responseId?: string; // new in 0.10.0
1022
+ responseModel?: string; // new in 0.10.0
807
1023
  usage?: Partial<ModelUsage>;
808
1024
  providerUsage?: Record<string, unknown>;
809
1025
  };
@@ -815,8 +1031,10 @@ type ModelReply = {
815
1031
  | `calls` | The tool calls of this reply, in order. `[]` when there are none. |
816
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. |
817
1033
  | `finishReason` | Why the reply ended, in the provider's own word (`"STOP"`, `"length"`, `"end_turn"`). It becomes `result.finishReason`. |
818
- | `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. |
819
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. |
820
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. |
821
1039
  | `providerUsage` | The provider's own usage object, as it came. It becomes `result.lastUsage`. |
822
1040
 
@@ -887,6 +1105,8 @@ Tokens of one request, or summed over several.
887
1105
  type UsageTotals = ModelUsage & {
888
1106
  requests: number;
889
1107
  byModel: Record<string, ModelUsage & { requests: number }>;
1108
+ estimatedInputTokens?: number; // new in 0.10.0
1109
+ unmeasuredRequests?: number; // new in 0.10.0
890
1110
  };
891
1111
  ```
892
1112
 
@@ -898,6 +1118,8 @@ in all and by model.
898
1118
  | `inputTokens`, `cachedInputTokens`, `outputTokens`, `thoughtTokens` | The sums over every request, as in [`ModelUsage`](#modelusage). |
899
1119
  | `requests` | Requests that were answered. One that failed and was sent again counts once; one that failed in the end does not count. |
900
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. |
901
1123
 
902
1124
  Guide: [costs and limits](../guides/costs-and-limits.md).
903
1125
 
@@ -906,14 +1128,17 @@ Guide: [costs and limits](../guides/costs-and-limits.md).
906
1128
  ```ts
907
1129
  declare class UsageMeter {
908
1130
  readonly totals: UsageTotals;
909
- add(model: string, usage: Partial<ModelUsage> | undefined): void;
1131
+ add(model: string, usage: Partial<ModelUsage> | undefined, estimatedInputTokens?: number): void;
910
1132
  }
911
1133
  ```
912
1134
 
913
1135
  Sums the usage of the requests of one question: `askWithFiles` uses one, and you can use one in a
914
1136
  loop of your own. `totals` starts at zero, with an empty `byModel`. `add` counts one request in
915
1137
  `totals` and in `totals.byModel[model]`, and adds each field of `usage` that is a finite number
916
- 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.
917
1142
 
918
1143
  ```ts
919
1144
  import { UsageMeter } from "llm-large-files";
@@ -948,20 +1173,22 @@ type Evidence = {
948
1173
  ```
949
1174
 
950
1175
  What one tool call showed the model of one document: `result.evidence` holds one for each call
951
- 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.
952
1179
 
953
1180
  | Field | What it holds |
954
1181
  |---|---|
955
- | `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). |
956
1183
  | `documentId` | The document's ID. |
957
1184
  | `document` | The file's name, when the result gave it. |
958
- | `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). |
959
1186
  | `pages` | The pages it looked at (`view_pages`), or the pages those lines are on, where the tool said. |
960
1187
  | `query` | What was searched for, or the task of a whole-file read. |
961
1188
  | `mode` | `"keywords"`, `"exact"` or `"regex"`, for a search. |
962
1189
  | `totalMatchingLines` | For an exact or regex search: how many lines match in the whole file, often more than were shown. |
963
- | `whole` | True for a whole-file read: other model requests read every line, and the model saw their answer. It has no `lines`. |
964
- | `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. |
965
1192
 
966
1193
  ```ts
967
1194
  import { mergeRanges, type AskResult, type NumberRange } from "llm-large-files";
@@ -338,7 +338,10 @@ should not have given, or should have: the same call fails again. The message of
338
338
  The library throws `"read"` from every look-up, `"write"` from `files.ingest` (code `"ETIMEDOUT"`
339
339
  for a write that did not end within `ingestTimeoutMs`), `"delete"` from `files.delete` and
340
340
  `"sweep"` from `files.sweep`. Until 0.9.0 the errors of writes came out as the store threw them. A
341
- `DocumentScopeError` the store throws is never wrapped.
341
+ `DocumentScopeError` the store throws is never wrapped. Since 0.10.0 a store call that does not end
342
+ within `storeTimeoutMs` (30 s by default) is one of code `"ETIMEDOUT"`, and one refused at once
343
+ because `maxStuckStoreCalls` calls of the process are stuck is one of code `"STORE_STUCK"`
344
+ ([`LargeFilesOptions`](./library.md#largefilesoptions)).
342
345
 
343
346
  #### Telling errors apart across copies of the package
344
347
 
@@ -408,7 +411,8 @@ provider's words.
408
411
  | An `AbortError` (a signal that aborted: the user left, the server stopped the question) | `"aborted"` | `"aborted"` | 503 | `true` | "It was stopped before it finished." |
409
412
  | A `TimeoutError` (`AbortSignal.timeout`, a deadline) | `"aborted"` | `"timeout"` | 504 | `true` | "It took too long, and was stopped. Try again." |
410
413
  | `DocumentScopeError` `"scope_invalid"` or `"scope_required"`, a `TypeError`, a `RangeError`, and their `EventError` | `"input"` | the scope error's code | 500 | `false` | "Something went wrong." It is a bug of the server, not something the user did. |
411
- | A Node system error (a `code` and a `syscall`), such as a path `ingest` does not read (`ELOOP`, `EISDIR`, `EINVAL`, `ENOENT`, `ETIMEDOUT`), and its `EventError` | `"unknown"` | its code: `"ENOSPC"`, when it reads as one (capitals, digits and `_`). A code that does not, such as a host, is left out | 500 | `false` | "Something went wrong (ENOSPC).", or "Something went wrong." without a code |
414
+ | A Node system error (a `code` and a `syscall`), such as a path `ingest` does not read (`ELOOP`, `EISDIR`, `EINVAL`, `ENOENT`), and its `EventError` | `"unknown"` | its code: `"EACCES"`, when it reads as one (capitals, digits and `_`). A code that does not, such as a host, is left out | 500 | `false` | "Something went wrong (EACCES).", or "Something went wrong." without a code |
415
+ | A Node system error whose code says the server, or a service it needs, could not answer just now ([transient](#transient-system-errors)), and its `EventError`. New in 0.10.0 | `"unknown"` | its code: `"ETIMEDOUT"`, `"ECONNRESET"`… | 503 | `true`, `retryAfterMs` 5,000; for a full disk (`ENOSPC`, `EDQUOT`) 30,000 | "The server could not do this just now (ETIMEDOUT). Try again in a moment."; for a full disk "The server has no room right now (ENOSPC). Try again later." |
412
416
  | Plain data (an `EventError`) without a `kind`, and without a `code` or `name` of the rows above | `"unknown"` | none | its `status` when it is 400 to 599, else 500 | `true` for 429, 502, 503 and 504 | "Something went wrong." |
413
417
  | Anything else | `"unknown"` | none | 500 | `false` | "Something went wrong." |
414
418
 
@@ -417,6 +421,30 @@ The statuses of model errors are those a server that asks a model for its user a
417
421
  The upload handlers answer with [`uploadAnswerOf`](./node.md#uploadansweroferror), which follows
418
422
  the same rules for the library's errors and keeps the message of an error with a status.
419
423
 
424
+ #### Transient system errors
425
+
426
+ New in 0.10.0. A Node system error (one with a `code` and a `syscall`) whose code says that the
427
+ server, or a service it needs, could not answer just now is read as one to retry: `errorInfoOf`
428
+ gives status 503, `retryable: true` and `retryAfterMs` 5,000, and the upload handlers answer it
429
+ `503` with `Retry-After: 5`. A full disk is retryable too, later: 30,000 and `Retry-After: 30`.
430
+ Before 0.10.0 they were `"unknown"`, 500, and not retryable.
431
+
432
+ | Code | What it says |
433
+ |---|---|
434
+ | `ETIMEDOUT` | A call that did not answer in time: a volume, a connection, a path upload whose read did not answer within `ingestTimeoutMs` (new in 0.10.0: it was the `IngestError` `"timeout"`, 422) |
435
+ | `ECONNRESET`, `EPIPE` | A connection cut by the other end |
436
+ | `ECONNREFUSED`, `EHOSTUNREACH`, `ENETUNREACH` | A service, a host or a network that could not be reached |
437
+ | `EAI_AGAIN` | A name that could not be looked up just now |
438
+ | `EAGAIN`, `EBUSY` | A resource busy for a moment |
439
+ | `EMFILE`, `ENFILE` | Too many files open, in the process or the system |
440
+ | `ESTALE` | A handle to a file of a network volume that the server no longer knows |
441
+ | `ENOSPC`, `EDQUOT` | A full disk, or a quota reached: 30 s to wait |
442
+
443
+ The code is read from the error itself, and from the library's words for it in an `EventError`
444
+ ("Upload failed (ETIMEDOUT).", "The file could not be read from storage (ETIMEDOUT)."), whatever
445
+ status that data holds: the `ingest.error` of a 0.9 upload handler said 500. Other codes keep the
446
+ row above: 500, not retryable. A store's error is a `DocumentStoreError`, 503 whatever its code.
447
+
420
448
  #### Your own words, in one switch
421
449
 
422
450
  Switch on `category`, and on `code` where you want more detail. This one answers a Hebrew-speaking