llm-large-files 0.5.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,1001 @@
1
+ # Events
2
+
3
+ This is the reference for the event stream of `llm-large-files`: typed events, in order, for
4
+ everything a question or an ingest does while it runs. It lists every event and its fields, the
5
+ rules of their order, how they map to the callbacks of earlier versions, what they carry of errors
6
+ and documents, `askStream` and `eventStream`, the events of an ingest, Server-Sent Events with
7
+ `writeSseEvents`, and the hooks of a tool call for a loop of your own. It is for you if you show a
8
+ question's progress in a page, send it to a browser, or log and trace what the library does. New
9
+ in 0.7.0.
10
+
11
+ ```ts
12
+ import { askStream, askWithFiles, eventStream, newRunId } from "llm-large-files";
13
+ import type {
14
+ AskEvent, IngestEvent, LibraryEvent, EventBase, EventError, EventResult, EventStream,
15
+ DocumentRef, IngestStage, NoticeCode, NoticeDisplay, RequestPurpose, RequestRole, ToolOutcome,
16
+ ExtractProgress, ToolCallHooks, ToolRequestHandle, ToolRequestStart, ToolRequestEnd,
17
+ } from "llm-large-files";
18
+ import { sseMessageOf, writeSseEvents } from "llm-large-files/node";
19
+ import type { SseMessage, SseWriteOptions } from "llm-large-files/node";
20
+ ```
21
+
22
+ `llm-large-files/gemini` re-exports the type `AskEvent`. It is the same type, documented here.
23
+
24
+ Contents:
25
+
26
+ - **Start:** [Events or callbacks](#events-or-callbacks), [The envelope](#the-envelope),
27
+ [A question, event by event](#a-question-event-by-event)
28
+ - **The events of a question:** [`AskEvent`](#askevent), [The order of the events](#the-order-of-the-events),
29
+ [`RequestRole` and `RequestPurpose`](#requestrole-and-requestpurpose),
30
+ [`ToolOutcome`](#tooloutcome), [`NoticeCode` and `NoticeDisplay`](#noticecode-and-noticedisplay),
31
+ [How the callbacks map to events](#how-the-callbacks-map-to-events)
32
+ - **What events carry:** [Errors: `EventError`](#errors-eventerror),
33
+ [Documents: `eventResults` and `EventResult`](#documents-eventresults-and-eventresult),
34
+ [A listener that throws](#a-listener-that-throws)
35
+ - **Reading events:** [`askStream(options)`](#askstreamoptions),
36
+ [`eventStream(run, options?)`](#eventstreamrun-options), [`streamText`](#streamtext),
37
+ [`askGemini`](#askgemini)
38
+ - **To a browser:** [`writeSseEvents(response, events, options?)`](#writesseeventsresponse-events-options),
39
+ [`sseMessageOf(event)`](#ssemessageofevent)
40
+ - **Ingest:** [`IngestEvent`](#ingestevent), [Stages and units](#stages-and-units),
41
+ [Uploads with progress](#uploads-with-progress),
42
+ [`ExtractInput.onProgress`, for an extractor of your own](#extractinputonprogress-for-an-extractor-of-your-own)
43
+ - **Your own loop:** [`ToolCallHooks`](#toolcallhooks)
44
+
45
+ ## Events or callbacks
46
+
47
+ `askWithFiles` and `askGemini` still take `onText`, `onActivity` and `onStep`. They get the same
48
+ strings as in 0.6.0, at the same moments, with or without `onEvent`. Use them for a status line and
49
+ a list of steps.
50
+
51
+ Use events when you need more than strings:
52
+
53
+ - which tool call or model request a line belongs to, with ids that pair each start with its end;
54
+ - how each tool call ended (`ok`, `error`, `refused`…), how long it took, and what it showed;
55
+ - each model request: which model, why it was made, its usage, its retries and how it ended;
56
+ - the plan, the notices the callbacks never got, and the result at the end;
57
+ - one ordered stream to send to a browser, write to a log or turn into traces.
58
+
59
+ You can pass both: the callbacks run as before, and the events say the same things with more
60
+ detail. The events of a question come from `AskOptions.onEvent` or `askStream`; those of an ingest
61
+ from `IngestInput.onEvent` or an upload with `Accept: text/event-stream`.
62
+
63
+ ```ts
64
+ import { askWithFiles, type AskEvent, type LargeFiles } from "llm-large-files";
65
+ import { gemini, geminiApi } from "llm-large-files/gemini";
66
+
67
+ const model = gemini(geminiApi({ apiKey: process.env.GEMINI_API_KEY!, model: "gemini-3.8-flash" }));
68
+
69
+ export async function answer(files: LargeFiles, documentIds: string[], question: string) {
70
+ return askWithFiles({
71
+ files, model, documentIds,
72
+ messages: [{ role: "user", text: question }],
73
+ onText: (delta) => process.stdout.write(delta),
74
+ onEvent: (event: AskEvent) => {
75
+ if (event.type === "request.end") console.error(event.requestId, event.outcome, `${event.ms} ms`, event.usage ?? "");
76
+ if (event.type === "tool.end") console.error(event.callId, event.outcome, event.step ?? event.error ?? "");
77
+ if (event.type === "notice") console.error(`[${event.code}] ${event.message}`);
78
+ },
79
+ });
80
+ }
81
+ ```
82
+
83
+ The options that turn events on:
84
+
85
+ | Option | Type | Default | What it does |
86
+ |---|---|---|---|
87
+ | `AskOptions.onEvent` | `(event: AskEvent) => void` | none | Gets every event of the question, in order. It does not change how the model is asked (see [`streamText`](#streamtext)). A throw from it ends the question with that error. |
88
+ | `AskOptions.runId` | `string` | `"run_"` and 16 hex digits | The `runId` of the events. Pass your own to tie them to a request of your app. |
89
+ | `AskOptions.eventResults` | `boolean` | `false` | Put each tool result in its `tool.end` event, and the tool rounds in the result of `run.finish` and `run.error`. They hold document text: see [Documents](#documents-eventresults-and-eventresult). |
90
+ | `AskOptions.streamText` | `boolean` | `true` with `onText` or in `askStream`, `false` otherwise | Whether the model is asked for the answer as it is written. See [`streamText`](#streamtext). |
91
+ | `IngestInput.onEvent` | `(event: IngestEvent) => void` | none | Gets every event of the ingest, in order. A throw from it ends the ingest with that error, and nothing is stored. |
92
+ | `IngestInput.runId` | `string` | `"ing_"` and 16 hex digits | The `runId` of the ingest's events. |
93
+
94
+ `askGemini` takes `onEvent`, `runId`, `eventResults` and `streamText` too, and passes them on.
95
+
96
+ ## The envelope
97
+
98
+ Every event is a plain object with a `type` and the fields of `EventBase`:
99
+
100
+ | Field | Type | What it holds |
101
+ |---|---|---|
102
+ | `seq` | `number` | 1 for the first event of a run, then one more for each event: no gaps, no repeats. |
103
+ | `runId` | `string` | The run the event belongs to: the `runId` you gave, or one made for it, `"run_…"` for a question and `"ing_…"` for an ingest. |
104
+ | `time` | `number` | When it was emitted, in milliseconds since 1970 (`Date.now()`). |
105
+
106
+ A run is one call of `askWithFiles` (or `askGemini`, or `askStream`) or of `files.ingest`. A
107
+ question that is planned again after its first request was too large is still one run.
108
+
109
+ `newRunId(prefix?)` makes an id the same way: the prefix (`"run"` by default), `_` and 16 hex
110
+ digits, such as `"run_3f9a0c1d2e4b5a67"`.
111
+
112
+ Events are JSON as they are, but for the result in `run.finish` and `run.error`, which can be large:
113
+ [`sseMessageOf`](#ssemessageofevent) makes it smaller. `LibraryEvent` is `AskEvent | IngestEvent`.
114
+
115
+ ## A question, event by event
116
+
117
+ A question about a log too large to send whole, with one model and no explorer. The model searches
118
+ once, then answers. These are the `data:` lines that `writeSseEvents` sends, one per event:
119
+
120
+ ```json
121
+ {"type":"run.start","models":{"answer":"gemini-3.8-flash"},"documentIds":["doc_6f1e2a9c4b7d4e0f8a3b5c7d9e1f2a3b"],"seq":1,"runId":"run_3f9a0c1d2e4b5a67","time":1795374302612}
122
+ {"type":"plan","inline":[],"searchable":[{"id":"doc_6f1e2a9c4b7d4e0f8a3b5c7d9e1f2a3b","name":"app.log","format":"log","estimatedTokens":325681}],"seq":2,"runId":"run_3f9a0c1d2e4b5a67","time":1795374302638}
123
+ {"type":"notice","code":"searching_instead","message":"Too large to read at once: app.log. Searching instead…","display":"activity","seq":3,"runId":"run_3f9a0c1d2e4b5a67","time":1795374302640}
124
+ {"type":"request.start","requestId":"req_1","role":"tools","purpose":"turn","model":"gemini-3.8-flash","turn":1,"estimatedInputTokens":5023,"seq":4,"runId":"run_3f9a0c1d2e4b5a67","time":1795374302640}
125
+ {"type":"request.end","requestId":"req_1","ms":1210,"outcome":"ok","usage":{"inputTokens":1800,"outputTokens":24},"finish":"complete","finishReason":"STOP","toolCalls":1,"seq":5,"runId":"run_3f9a0c1d2e4b5a67","time":1795374303850}
126
+ {"type":"tool.start","callId":"call_1","providerCallId":"fc_1","tool":"search_document","args":{"document_id":"doc_6f1e2a9c4b7d4e0f8a3b5c7d9e1f2a3b","query":"ERROR","mode":"exact","max_results":3},"label":"Search app.log (exact) for “ERROR”","documentId":"doc_6f1e2a9c4b7d4e0f8a3b5c7d9e1f2a3b","round":1,"seq":6,"runId":"run_3f9a0c1d2e4b5a67","time":1795374303851}
127
+ {"type":"tool.end","callId":"call_1","outcome":"ok","ms":4,"step":"Search app.log (exact) for “ERROR” — 51 matching lines","evidence":{"tool":"search_document","documentId":"doc_6f1e2a9c4b7d4e0f8a3b5c7d9e1f2a3b","document":"app.log","lines":[[97,97],[194,194],[291,291],[4947,4947]],"query":"ERROR","mode":"exact","totalMatchingLines":51,"callId":"call_1"},"resultCharacters":672,"seq":7,"runId":"run_3f9a0c1d2e4b5a67","time":1795374303855}
128
+ {"type":"request.start","requestId":"req_2","role":"tools","purpose":"turn","model":"gemini-3.8-flash","turn":2,"estimatedInputTokens":5461,"seq":8,"runId":"run_3f9a0c1d2e4b5a67","time":1795374303855}
129
+ {"type":"text","requestId":"req_2","delta":"The first error is at line 97.","seq":9,"runId":"run_3f9a0c1d2e4b5a67","time":1795374304630}
130
+ {"type":"request.end","requestId":"req_2","ms":775,"outcome":"ok","usage":{"inputTokens":2600,"outputTokens":12},"finish":"complete","finishReason":"STOP","toolCalls":0,"seq":10,"runId":"run_3f9a0c1d2e4b5a67","time":1795374304630}
131
+ {"type":"run.finish","seq":11,"runId":"run_3f9a0c1d2e4b5a67","time":1795374304631,"result":{"answered":true,"text":"The first error is at line 97.","finishReason":"STOP","steps":["Search app.log (exact) for “ERROR” — 51 matching lines"],"evidence":[{"tool":"search_document","documentId":"doc_6f1e2a9c4b7d4e0f8a3b5c7d9e1f2a3b","document":"app.log","lines":[[97,97],[194,194],[291,291],[4947,4947]],"query":"ERROR","mode":"exact","totalMatchingLines":51,"callId":"call_1"}],"turns":2,"usage":{"requests":2,"inputTokens":4400,"cachedInputTokens":0,"outputTokens":36,"thoughtTokens":0,"byModel":{"gemini-3.8-flash":{"requests":2,"inputTokens":4400,"cachedInputTokens":0,"outputTokens":36,"thoughtTokens":0}}}}}
132
+ ```
133
+
134
+ What to see in it:
135
+
136
+ - The second request is the answer: its reply has text and no tool call. It is still `role`
137
+ `"tools"`, `purpose` `"turn"`, as a model that may call tools.
138
+ - The text came in one piece, once the reply was in, because this question was asked with
139
+ `streamText: false` (`askStream({ ..., streamText: false })`; `onEvent` alone, without `onText`,
140
+ does the same). With `onText`, in `askStream` by default, or with `streamText: true`, it comes in
141
+ many `text` events as it is written.
142
+ - `onEvent` gets the same 11 events. Its `run.finish` holds the whole result, without
143
+ `toolTurns`: `writeSseEvents` sends a smaller one (see [`sseMessageOf`](#ssemessageofevent)).
144
+
145
+ ## The events of a question
146
+
147
+ ### `AskEvent`
148
+
149
+ The events of `askWithFiles`, `askGemini` and `askStream`, by `type`:
150
+
151
+ | `type` | When |
152
+ |---|---|
153
+ | [`run.start`](#runstart) | Always first. |
154
+ | [`plan`](#plan) | After `run.start`, before any request. Again after a `replanned` notice. |
155
+ | [`request.start`](#requeststart) | A model request starts: a turn of the chat, or one request of a whole-file read. |
156
+ | [`retry`](#retry) | That request failed and is sent again after a wait. |
157
+ | [`text`](#text) | Answer text arrives. |
158
+ | [`request.end`](#requestend) | The request ended, after any retries. |
159
+ | [`tool.start`](#toolstart) | A tool call starts to run, or is settled without running. |
160
+ | [`tool.progress`](#toolprogress) | Progress of a long tool call: a whole-file read. |
161
+ | [`tool.end`](#toolend) | The tool call ended. |
162
+ | [`notice`](#notice) | Something the question did that is not a request or a tool call. |
163
+ | [`run.finish`](#runfinish) | Always last when the question returns. |
164
+ | [`run.error`](#runerror) | Always last when the question throws, an abort included. |
165
+
166
+ Each event also has `seq`, `runId` and `time` ([the envelope](#the-envelope)). Fields marked
167
+ optional are left out, not set to `undefined`, unless the table says so.
168
+
169
+ #### `run.start`
170
+
171
+ | Field | Type | What it holds |
172
+ |---|---|---|
173
+ | `models` | `{ answer: string; explorer?: string }` | The adapter ids: the model that answers, and the explorer when there is one that is not the same adapter. `answer` is `""` when `model` is missing. |
174
+ | `documentIds` | `string[]` | The `documentIds` of the question, as given (a copy). `[]` when they are not an array. |
175
+
176
+ It is sent before the options are checked: a question whose options do not work sends `run.start`
177
+ and then `run.error`.
178
+
179
+ #### `plan`
180
+
181
+ | Field | Type | What it holds |
182
+ |---|---|---|
183
+ | `inline` | [`DocumentRef[]`](#documentref) | The documents whose whole text goes into the prompt. |
184
+ | `searchable` | [`DocumentRef[]`](#documentref) | The documents the model reaches through tools. |
185
+
186
+ ##### `DocumentRef`
187
+
188
+ | Field | Type | What it holds |
189
+ |---|---|---|
190
+ | `id` | `string` | The document ID. |
191
+ | `name` | `string` | The file name. |
192
+ | `format` | `DocumentFormat` | `"text"`, `"log"`, `"pdf"`… |
193
+ | `estimatedTokens` | `number` | The library's estimate of the document's tokens. |
194
+ | `pages` | `number`, optional | For a PDF, a PPTX or an XLSX (its sheets). |
195
+
196
+ #### `request.start`
197
+
198
+ | Field | Type | What it holds |
199
+ |---|---|---|
200
+ | `requestId` | `string` | Unique in the run: `"req_1"`, `"req_2"`… A question planned again goes on counting. |
201
+ | `role` | [`RequestRole`](#requestrole-and-requestpurpose) | Which model the request goes to: `"tools"`, `"explorer"`, `"answer"` or `"reader"`. |
202
+ | `purpose` | [`RequestPurpose`](#requestrole-and-requestpurpose) | Why it is made. |
203
+ | `model` | `string` | The adapter id of the model the request goes to. |
204
+ | `turn` | `number`, optional | For a request of the chat (not `"reader"`): its number in the question, from 1, as `AskResult.turns` counts. |
205
+ | `callId` | `string`, optional | For a `"reader"` request: the tool call of the whole-file read it belongs to. |
206
+ | `detail` | `string`, optional | For a `"reader"` request: `"part 3 of 12"`, `"first half of part 3 of 12"`, `"round 2: 1 of 4"` (combining notes), or `"the answer"`. |
207
+ | `estimatedInputTokens` | `number`, optional | For a request of the chat: the library's estimate of its input tokens, before it is sent. |
208
+
209
+ A request that the provider refused as too large, and that is made smaller and sent again, is two
210
+ requests: the first ends with `outcome: "error"` and `error.kind: "context_overflow"`, then a
211
+ `room_made` notice, then a new `request.start`.
212
+
213
+ #### `retry`
214
+
215
+ | Field | Type | What it holds |
216
+ |---|---|---|
217
+ | `requestId` | `string` | The request sent again. |
218
+ | `attempt` | `number` | 1 for the first retry. |
219
+ | `delayMs` | `number` | The wait before it is sent again. |
220
+ | `error` | [`EventError`](#errors-eventerror) | Why it failed, in words for users. |
221
+ | `message` | `string` | The line `onActivity` gets for a retry of a chat request: "The model did not answer (HTTP 503). Trying again…". |
222
+
223
+ The retries of a `"reader"` request (a whole-file read) are told only here: `onActivity` never got
224
+ them.
225
+
226
+ #### `text`
227
+
228
+ | Field | Type | What it holds |
229
+ |---|---|---|
230
+ | `requestId` | `string` | The request whose reply holds the text. |
231
+ | `delta` | `string` | The text, as `onText` gets it. |
232
+
233
+ Joined, the deltas of a run are `AskResult.text`. Only the text that is shown comes: the answering
234
+ model's, never an explorer's. When a later reply adds text, it starts with a delta of `"\n\n"`, as
235
+ for `onText`.
236
+
237
+ #### `request.end`
238
+
239
+ | Field | Type | What it holds |
240
+ |---|---|---|
241
+ | `requestId` | `string` | The request that ended. |
242
+ | `ms` | `number` | From `request.start` to now, retries and their waits included. |
243
+ | `outcome` | `"ok" \| "error"` | How it ended. |
244
+ | `usage` | `Partial<ModelUsage>`, optional | What the provider said this request used. For a `"reader"` request, the sum of all its sends. |
245
+ | `finish` | `"complete" \| "cut" \| "filtered" \| "malformed_call"`, optional | How the reply ended, in the library's words. Chat requests only. |
246
+ | `finishReason` | `string`, optional | How the reply ended, in the provider's words. Chat requests only. |
247
+ | `toolCalls` | `number`, optional | How many tool calls the reply asked for. Chat requests with outcome `"ok"`. |
248
+ | `error` | [`EventError`](#errors-eventerror), optional | With outcome `"error"`: why. |
249
+
250
+ A request that failed does not always end the question. An overflow is made smaller and sent
251
+ again, and a part of a whole-file read that fails is read in halves or reported to the model.
252
+
253
+ #### `tool.start`
254
+
255
+ | Field | Type | What it holds |
256
+ |---|---|---|
257
+ | `callId` | `string` | Unique in the run: `"call_1"`, `"call_2"`… in call order. |
258
+ | `providerCallId` | `string`, optional | The provider's own id of the call, when it sent one (`ToolCall.id`). |
259
+ | `tool` | `string` | The tool's name: `"search_document"`, `"read_document"`… |
260
+ | `args` | `Record<string, unknown>` | The arguments as the model sent them. |
261
+ | `label` | `string` | One line of plain text: "Search app.log (exact) for “timeout”". It can quote the model's words: show it as text, never as HTML. |
262
+ | `documentId` | `string`, optional | `args.document_id`, when it is a string. |
263
+ | `round` | `number` | The turn of the tool loop the call came in, from 1. |
264
+
265
+ A call that runs starts when it gets its turn to run. A call settled without running (refused,
266
+ answered with a pointer, not well formed, over `limits.callsPerTurn`) starts too, and ends with the
267
+ outcome that says so.
268
+
269
+ #### `tool.progress`
270
+
271
+ | Field | Type | What it holds |
272
+ |---|---|---|
273
+ | `callId` | `string` | The whole-file read. |
274
+ | `stage` | `"map" \| "reduce"` | `"map"`: parts read (requests with purpose `"part"`). `"reduce"`: notes combined, or the answer written (`"merge"`, `"final"`). |
275
+ | `done` | `number` | How many are done. |
276
+ | `total` | `number` | How many there are. |
277
+ | `message` | `string` | "Reading app.log: part 3 of 12". `onActivity` gets it with `"…"` after it. |
278
+
279
+ #### `tool.end`
280
+
281
+ | Field | Type | What it holds |
282
+ |---|---|---|
283
+ | `callId` | `string` | The call that ended. |
284
+ | `outcome` | [`ToolOutcome`](#tooloutcome) | How it ended. |
285
+ | `ms` | `number` | From `tool.start` to now. Ends come in call order, so this includes the wait for the calls before it in the turn. |
286
+ | `step` | `string`, optional | The finished step, as `onStep` got it. Absent for `"not_run"` (one `calls_not_run` notice says it for all of them), and for a call ended because its turn failed. |
287
+ | `evidence` | [`Evidence`](./ask.md#evidence), optional | What the call showed the model, with this `callId`. Each entry of `AskResult.evidence` has its `callId` too, so you can find the call it came from. |
288
+ | `resultCharacters` | `number`, optional | The characters of the JSON result the model was sent. 0 for a call ended because its turn failed. |
289
+ | `error` | `string`, optional | When the result the model was sent is an error (outcomes `"error"`, `"refused"`, `"not_run"`): its message. For a call ended because its turn failed: why, as in `EventError.message`. |
290
+ | `result` | [`ToolResult`](./tools.md#toolresult), optional | The result the model was sent. Only with `eventResults: true`: it holds document text. |
291
+
292
+ #### `notice`
293
+
294
+ | Field | Type | What it holds |
295
+ |---|---|---|
296
+ | `code` | [`NoticeCode`](#noticecode-and-noticedisplay) | What happened. |
297
+ | `message` | `string` | One line of plain text, word for word what the callback got when there was one. |
298
+ | `display` | [`NoticeDisplay`](#noticecode-and-noticedisplay) | Where it went in the callbacks: `"activity"`, `"step"` or `"none"`. |
299
+
300
+ #### `run.finish`
301
+
302
+ | Field | Type | What it holds |
303
+ |---|---|---|
304
+ | `result` | [`EventResult`](#documents-eventresults-and-eventresult) | A copy of the result `askWithFiles` returns, without `toolTurns` and with a plan that names the documents only, unless `eventResults: true`. |
305
+
306
+ Nothing comes after it.
307
+
308
+ #### `run.error`
309
+
310
+ | Field | Type | What it holds |
311
+ |---|---|---|
312
+ | `error` | [`EventError`](#errors-eventerror) | Why the question failed, in words for users. The error that is thrown keeps the provider's words. |
313
+ | `partial` | [`EventResult`](#documents-eventresults-and-eventresult), optional | What [`partialResultOf(error)`](./ask.md#partialresultoferror) gives: what the question found before it failed, without `toolTurns` unless `eventResults: true`. Absent for an error before the question was under way (a missing document, options that do not work). |
314
+
315
+ Nothing comes after it.
316
+
317
+ ### The order of the events
318
+
319
+ These hold for every run.
320
+
321
+ 1. **One run, counted.** `seq` goes 1, 2, 3… without gaps, and every event has the same `runId`.
322
+ 2. **First and last.** `run.start` is always first. Exactly one terminal event, `run.finish` or
323
+ `run.error`, is always last. Nothing comes after it: work that goes on after a question
324
+ stopped, such as a part read whose adapter does not look at the signal, is never reported.
325
+ 3. **The plan before the requests.** `plan` comes after `run.start` and before the first
326
+ `request.start`. The `searching_instead` notice, when there is one, comes after it.
327
+ 4. **Requests in pairs.** Each `request.start` has one `request.end` with the same `requestId`,
328
+ after it. Its `retry` and `text` events come between them. A request that is made smaller and
329
+ sent again is a new request.
330
+ 5. **Tool calls in pairs.** Each `tool.start` has one `tool.end` with the same `callId`, after it.
331
+ Its `tool.progress` events come between them, and so do the `"reader"` requests of a whole-file
332
+ read, whose `callId` names it.
333
+ 6. **A turn's tool calls.** The `request.end` of the reply comes before the `tool.start` events of
334
+ its calls. The calls of one turn run a few at a time (up to four, and looks at pages one after
335
+ another), so their starts, progress and reader requests interleave. Their ends come in call
336
+ order: a call that finished early waits for the calls before it. Calls settled without running
337
+ start as soon as the turn is planned, before the calls that run. Calls over
338
+ `limits.callsPerTurn` start and end one after another, after the ends of the calls that ran,
339
+ and then comes one `calls_not_run` notice.
340
+ 7. **A failed turn.** When a turn fails (the question was stopped, or a listener threw), the calls
341
+ still open end with outcome `"error"`, in call order, and their reader requests end with them,
342
+ before `run.error`. Treat any start that has no end in a run that ended with `run.error` as
343
+ ended by it.
344
+ 8. **Planned again is one run.** When the first request was too large for the model and the
345
+ documents are planned again, the run goes on: one `run.start`, the first `plan`, the failed
346
+ `request.start` and `request.end`, a `replanned` notice, a second `plan`, and the rest.
347
+ `requestId`, `callId` and `turn` go on counting.
348
+ 9. **Notices where they happen.** `writing_answer` comes before the `request.start` of the
349
+ answer after the tools. `budget_reached` comes where the limit is reached: before the answer's
350
+ request when it stops the tools, or after the answer's `request.end` when it keeps the answer
351
+ from being asked for again. `no_room` and `results_shortened` come while a turn is planned,
352
+ before its `tool.start` events. `room_made`, `nudged` and `answer_again` come after the
353
+ `request.end` of the request they are about, before the next `request.start`. `blocked` comes
354
+ right after the `request.end` of the reply the provider refused.
355
+
356
+ ### `RequestRole` and `RequestPurpose`
357
+
358
+ `RequestRole`: which model a request goes to.
359
+
360
+ | Role | The request |
361
+ |---|---|
362
+ | `"tools"` | A turn of the one model of a question without an explorer, in which it may call tools. Its reply can also be the answer. |
363
+ | `"explorer"` | A turn of the explorer model, which only calls tools. |
364
+ | `"answer"` | A request of the model that writes the answer: the request after the tools, or the one request of a question that needs no tools. |
365
+ | `"reader"` | One request of a whole-file read (`analyze_whole_document`), made for one tool call. It goes to the model that explores. |
366
+
367
+ `RequestPurpose`: why a request is made.
368
+
369
+ | Purpose | Role | The request |
370
+ |---|---|---|
371
+ | `"turn"` | `"tools"`, `"explorer"` | A turn of the tool loop. |
372
+ | `"nudge"` | `"tools"`, `"explorer"` | The same turn asked again after an empty reply or a tool call that could not be read. |
373
+ | `"closing"` | `"answer"` | The request for the answer after the tools. |
374
+ | `"answer_again"` | `"answer"` | The answer asked for again after it came back without text. |
375
+ | `"direct"` | `"answer"` | The one request of a question that needs no tools: every document went in whole and no page can be looked at. |
376
+ | `"part"` | `"reader"` | A whole-file read reading one part, or half of one. |
377
+ | `"merge"` | `"reader"` | A whole-file read combining notes. |
378
+ | `"final"` | `"reader"` | A whole-file read writing its answer. |
379
+
380
+ ### `ToolOutcome`
381
+
382
+ How a tool call ended (`tool.end.outcome`):
383
+
384
+ | Outcome | The call |
385
+ |---|---|
386
+ | `"ok"` | Ran and returned a result. |
387
+ | `"error"` | Ran, or was checked, and returned `{ error }`: bad arguments, a document it cannot read, a regex that took too long, a call that did not arrive whole. Or it was ended because its turn failed (the question was stopped, or a listener threw): then the model was sent nothing. |
388
+ | `"refused"` | Was not run, for a limit of the question: its cost, the room left in the conversation, the reads of a whole file. |
389
+ | `"already_shown"` | Repeated a call whose result is still in the conversation, and was answered with a pointer to it. |
390
+ | `"not_run"` | Was over `limits.callsPerTurn` for its turn. |
391
+
392
+ ### `NoticeCode` and `NoticeDisplay`
393
+
394
+ `NoticeDisplay` says where a notice went in the callbacks: `"activity"` to `onActivity`, `"step"`
395
+ to `onStep` and `AskResult.steps`, `"none"` to neither. The `"none"` notices are new in 0.7.0.
396
+
397
+ | Code | Display | When | Message |
398
+ |---|---|---|---|
399
+ | `"searching_instead"` | activity | Documents too large to send whole are searched instead. | "Too large to read at once: app.log. Searching instead…" |
400
+ | `"writing_answer"` | activity | The tools are done and the answer is asked for. | "Writing the answer…" |
401
+ | `"replanned"` | step | The question started again with less in the prompt. | "The first request was larger than the model's window of 128,000 tokens: the files were planned again to fit it", or another wording of the same |
402
+ | `"room_made"` | step | The request was too large for the model, was made smaller and sent again. | "The request was larger than the model takes: older tool results were shortened, and it was sent again" |
403
+ | `"nudged"` | step | An empty or malformed reply was asked for again. | "The model's first reply was empty: it was asked again", "The model's tool call could not be read: it was asked to send it again" |
404
+ | `"results_shortened"` | step | Older tool results were shortened to make room. | "Older tool results were shortened to make room in the request" |
405
+ | `"answer_again"` | step | The answer came back without text and was asked for again. | "The model's answer was empty: it was asked again", "The model called a tool instead of answering: it was asked again for the answer" |
406
+ | `"calls_not_run"` | step | A turn had more calls than `limits.callsPerTurn`. | "2 more tool calls in this turn were not run (at most 8 a turn)" |
407
+ | `"budget_reached"` | none | `limits.inputTokens` or `limits.requests` was reached, so no more tools run, or the answer is not asked for again. Once a question. | "No more tools: the question reached its limit of input tokens or requests." |
408
+ | `"no_room"` | none | There is no room left in the conversation for another tool result. Once a question. | "There is no room left in this conversation for another tool result." |
409
+ | `"blocked"` | none | The provider refused the prompt (`AskResult.blockReason`). | "The provider refused the prompt: SAFETY." |
410
+
411
+ The messages are written for people and may change between versions. Test `code`, not `message`.
412
+
413
+ ### How the callbacks map to events
414
+
415
+ The callbacks of earlier versions get nothing the events do not also say:
416
+
417
+ | Callback | The events that say the same |
418
+ |---|---|
419
+ | `onText(delta)` | `text`: `delta` is the same string, and the deltas come in the same pieces. |
420
+ | `onActivity(line)` | `tool.start`: `label` + `"…"`, for a call that runs (a call settled without running was never told to `onActivity`). `tool.progress`: `message` + `"…"`. `notice` with `display: "activity"`: `message`. `retry` of a chat request (not `"reader"`): `message`. |
421
+ | `onStep(line)` | `tool.end`: `step`, when it is there. `notice` with `display: "step"`: `message`. Together, in order, they are `AskResult.steps`. |
422
+
423
+ So a page that showed the callbacks can show the events in their place. The example server
424
+ (`examples/server.ts`) does: a status line from `tool.start`, `tool.progress`, the `activity`
425
+ notices and `retry`; a list of the tool calls, each marked by its `outcome`, with a counter for
426
+ whole-file reads; and the answer from `text`.
427
+
428
+ ## What events carry
429
+
430
+ ### Errors: `EventError`
431
+
432
+ An error in an event is plain data, safe to send to a browser:
433
+
434
+ | Field | Type | What it holds |
435
+ |---|---|---|
436
+ | `message` | `string` | A message your users may see. |
437
+ | `kind` | `ModelErrorKind`, optional | For a model error: what kind it is (`errorKindOf`): `"rate_limit"`, `"timeout"`, `"auth"`… |
438
+ | `status` | `number`, optional | For an HTTP error: its status. 0 when no answer came. |
439
+ | `name` | `string`, optional | The error's class name: `"ModelRequestError"`, `"AbortError"`, `"DocumentsNotFoundError"`, `"IngestError"`… |
440
+ | `code` | `IngestErrorCode`, optional | For a file `ingest` could not read: why, as [`IngestError.code`](./library.md#ingesterror) (`"too_large"`, `"no_text"`, `"hostile"`, `"busy"`…), so that a page can say it in its own words. New in 0.8.0. |
441
+
442
+ How `message` is written:
443
+
444
+ - **A model error** (one with a `kind` or a numeric `status`) is told by its kind and status, in
445
+ the library's words: "The model was busy (HTTP 429).", "The model failed on its side (HTTP
446
+ 503).", "The model refused the key or token it was sent (HTTP 401).". The provider's own words
447
+ can name projects, hosts or keys: they stay on the error that is thrown, for your logs.
448
+ - **A storage error** (`DocumentStoreError`) is told by its own message, which names only the
449
+ code. **A Node system error** (one with a `code` and a `syscall`) is told as "The file could not
450
+ be read from storage (ENOENT).".
451
+ - **Any other `Error`** is told by its message as it is written: the library's own refusals and
452
+ messages ("app.log is empty."), and the reason of an abort. That includes errors your own code
453
+ throws: an adapter, an extractor or a listener of your own. Keep secrets out of their messages,
454
+ or give them a `status`.
455
+ - **Anything that is not an `Error`** is told as "Something went wrong.".
456
+
457
+ An [`IngestError`](./library.md#ingesterror) is told by its message, with `name: "IngestError"` and
458
+ its `code`, and with its `status` only for `"too_large"` (413) and `"busy"` (503): that status is the
459
+ answer of an upload, not of a model, and the others are all 422. Until 0.8.0 the same refusals were
460
+ plain `Error`s, and their events said `name: "Error"`; a test that expects that needs
461
+ `"IngestError"`. A store that failed, an abort and a listener that threw have no `code`.
462
+
463
+ Where errors appear: `retry.error`, `request.end.error`, `run.error.error` and `ingest.error.error`
464
+ are `EventError`s. `tool.end.error` is a string: the error the model was sent, or, for a call
465
+ ended because its turn failed, the `message` of the turn's error. An ingest whose store failed to
466
+ write the document says only "The document could not be stored. Try again later.", whatever the
467
+ store threw.
468
+
469
+ To show your own words, map the error by `kind` and `name`, as `examples/server.ts` does in its
470
+ `userMessage`, and the error of an ingest by `code`. [Errors and reliability](../guides/errors-and-reliability.md) says what each kind
471
+ means.
472
+
473
+ ### Documents: `eventResults` and `EventResult`
474
+
475
+ Events are often sent on to a browser, so by default they carry no tool results, which hold the
476
+ text of the documents:
477
+
478
+ - `tool.end` has no `result`;
479
+ - the result in `run.finish` and `run.error` has no `toolTurns`, and its `plan` names each
480
+ document as a [`DocumentRef`](#plan) (id, name, format, estimated tokens, pages) instead of its
481
+ full `DocumentMeta`, which holds the `owner`, the headings of the outline and, for a log, the
482
+ templates of its most frequent lines.
483
+
484
+ ```ts
485
+ type EventResult = Omit<AskResult, "toolTurns" | "plan"> & {
486
+ toolTurns?: ToolTurn[];
487
+ plan: { inline: Array<DocumentRef | DocumentMeta>; searchable: Array<DocumentRef | DocumentMeta> };
488
+ };
489
+ ```
490
+
491
+ With `eventResults: true`, `tool.end.result` is the result the model was sent, and
492
+ `run.finish.result` and `run.error.partial` have `toolTurns` and the full plan. Use it for a log or an
493
+ audit trail on your server, not for a browser. The result `askWithFiles` returns, `askStream`'s
494
+ `result`, and `partialResultOf(error)` always have `toolTurns`: keep them from there, with the
495
+ conversation.
496
+
497
+ What events carry without `eventResults`, and you should know before you send them on:
498
+
499
+ - `tool.start.args` and `label`, `tool.end.step` and `evidence.query`: what the model asked for, in
500
+ its words, which can quote the documents.
501
+ - `text`, `run.finish.result.text` and `steps`: the answer and the steps.
502
+ - `plan` (the event, and `plan` in the result): the name, format, size and pages of each document.
503
+ - `run.finish.result` and `run.error.partial` whole: besides the answer, `budget` and `lastUsage`,
504
+ the provider's own usage report. [`sseMessageOf`](#ssemessageofevent), the default of
505
+ `writeSseEvents`, leaves these out.
506
+
507
+ ### A listener that throws
508
+
509
+ A throw from `onEvent` is not swallowed: it ends the question with that error, as a throw from
510
+ `onText`, `onActivity` or `onStep` does. What is under way is ended first, and the events say so:
511
+
512
+ - A throw on a `request.start` ends that request (`request.end` with outcome `"error"`) before it
513
+ is sent.
514
+ - A throw on a `tool.start`, or anywhere in a turn, ends the turn: its calls that wait for a slot
515
+ do not run, the calls still running are stopped, and the open ones end with outcome `"error"`.
516
+ - A throw from `onEvent` or `onActivity` while a whole-file read runs (its progress, its requests,
517
+ their retries) ends the question with that error. **Changed in 0.7.0:** 0.6.0 turned a throw of
518
+ `onActivity` there into the tool's error, which the model was sent and the question went on.
519
+ - A throw on `run.finish` makes `askWithFiles` throw that error: the answer is lost. A throw on
520
+ `run.error` is thrown in place of the question's own error.
521
+ - A throw from `IngestInput.onEvent` ends the ingest with that error, and stores nothing. On
522
+ `ingest.finish` too: the document just stored is deleted.
523
+
524
+ Keep listeners from throwing. When a listener sends events over a network, catch its errors
525
+ there.
526
+
527
+ ## Reading events
528
+
529
+ ### askStream(options)
530
+
531
+ ```ts
532
+ declare function askStream(options: AskOptions): EventStream<AskEvent, AskResult>;
533
+ ```
534
+
535
+ `askWithFiles` as a stream of its events. It starts the question at once and returns an
536
+ [`EventStream`](#eventstreamrun-options): an async iterable of the events, its `result`, and
537
+ `abort()`.
538
+
539
+ - `streamText` defaults to `true`: the model is asked for the answer as it is written, so `text`
540
+ events come as it is written. Pass `streamText: false` to ask as `askWithFiles` does without
541
+ `onText`.
542
+ - `options.onEvent`, when given, gets each event too, after the stream. A throw from it ends the
543
+ question, but the stream still gets that event, and then `run.error`. A throw on `run.finish`
544
+ leaves the stream ending with `run.finish`, and `result` rejects.
545
+ - `options.signal` stops the question, as for `askWithFiles`.
546
+
547
+ ```ts
548
+ import { askStream } from "llm-large-files";
549
+
550
+ // Assumed: files, model and documentIds are those of the chat being answered.
551
+ const stream = askStream({ files, model, documentIds, messages: [{ role: "user", text: "What failed first?" }] });
552
+ for await (const event of stream) {
553
+ if (event.type === "tool.start") console.error(`${event.label}…`);
554
+ if (event.type === "text") process.stdout.write(event.delta);
555
+ if (event.type === "run.error") console.error(`\nFailed: ${event.error.message}`);
556
+ }
557
+ // The loop never throws. The result does, with the question's error.
558
+ const result = await stream.result.catch(() => undefined);
559
+ if (result) console.error(`\n${result.usage.requests} requests, ${result.usage.inputTokens} input tokens`);
560
+ ```
561
+
562
+ ### eventStream(run, options?)
563
+
564
+ ```ts
565
+ declare function eventStream<E, T>(
566
+ run: (onEvent: (event: E) => void, signal: AbortSignal) => Promise<T>,
567
+ options?: { signal?: AbortSignal | undefined },
568
+ ): EventStream<E, T>;
569
+
570
+ type EventStream<E, T> = AsyncIterable<E> & {
571
+ result: Promise<T>;
572
+ abort(reason?: unknown): void;
573
+ };
574
+ ```
575
+
576
+ Runs `run` at once, with a listener and a signal, and gives what it emits as an async iterable.
577
+ `askStream` is `eventStream` around `askWithFiles`; the upload handler uses it around
578
+ `files.ingest`. Use it for any function that takes an `onEvent` and a `signal`.
579
+
580
+ | Parameter | Type | Default | What it does |
581
+ |---|---|---|---|
582
+ | `run` | `(onEvent, signal) => Promise<T>` | required | The run. Pass `onEvent` and `signal` on to it. A throw from it, at once or later, rejects `result`. |
583
+ | `options.signal` | `AbortSignal` | none | Aborts `signal` when it aborts. |
584
+
585
+ How the stream behaves:
586
+
587
+ - **Read once.** The events wait in memory until they are read: read them, or call `abort()`.
588
+ A second `for await` over the same stream throws a `TypeError`: "These events can be read once."
589
+ - **Leaving the loop stops the run.** A `break`, a `return` or a throw in the loop aborts
590
+ `signal` with an `AbortError` ("The events stopped being read."). `result` then rejects with
591
+ it, and the events after it are dropped.
592
+ - **The iterable never throws.** It ends after the run's last event, whether the run returned or
593
+ failed. To know how it ended, read the terminal event (`run.error`, `ingest.error`), or await
594
+ `result`.
595
+ - **`result`** is what the run returned. It rejects with the run's error. Awaiting it is
596
+ optional: it never goes unhandled.
597
+ - **`abort(reason?)`** aborts `signal` with `reason`, or an `AbortError` ("The run was stopped.").
598
+ The stream ends after the run's last event, such as `run.error`.
599
+
600
+ ### `streamText`
601
+
602
+ `streamText` decides how the model is asked for the answer. `onEvent` alone never changes it:
603
+
604
+ | `streamText` | The model is asked | `text` events |
605
+ |---|---|---|
606
+ | `true` | With the adapter's streaming request, when it can stream (`gemini()` with an endpoint that has `streamUrl`, `openAiCompatible()` and `anthropic()` unless `stream: false`). | Many, as the answer is written. From an adapter that cannot stream, once the reply is in: one, or from `gemini()` without `streamUrl`, one for each text part. |
607
+ | `false` | With a request whose reply comes whole (`anthropic()` still streams unless `stream: false`, but passes nothing on as it comes). | One for each reply that has text, once the reply is in. |
608
+
609
+ It defaults to `true` when `onText` is given and in `askStream`, and to `false` otherwise.
610
+ `streamText: false` with `onText` gets the text once each reply is in, in one piece. Either way, a
611
+ reply whose text follows earlier text of the question comes after a `"\n\n"` delta of its own.
612
+
613
+ Two things change with it. A streamed reply that fails after its first piece of text is not sent
614
+ again: the question throws, since the user has seen part of an answer. And a reply that is not
615
+ streamed must be written within the adapter's `firstByteTimeoutMs`, since nothing arrives until
616
+ it is done ([Waits on a silent model](../guides/errors-and-reliability.md#waits-on-a-silent-model)).
617
+ An explorer's requests are never streamed: their text is not shown.
618
+
619
+ ### `askGemini`
620
+
621
+ `askGemini` takes `onEvent`, `runId`, `eventResults` and `streamText`, and passes them to
622
+ `askWithFiles`. There is no `askGemini` stream: make one with `eventStream`.
623
+
624
+ ```ts
625
+ import { eventStream, type AskEvent } from "llm-large-files";
626
+ import { askGemini, type AskGeminiOptions, type AskGeminiResult } from "llm-large-files/gemini";
627
+
628
+ /** askGemini as a stream of its events, as askStream is for askWithFiles. */
629
+ export function askGeminiStream(options: AskGeminiOptions) {
630
+ return eventStream<AskEvent, AskGeminiResult>(
631
+ (onEvent, signal) => askGemini({
632
+ ...options,
633
+ streamText: options.streamText !== false,
634
+ signal,
635
+ onEvent: (event) => {
636
+ onEvent(event);
637
+ options.onEvent?.(event);
638
+ },
639
+ }),
640
+ { signal: options.signal },
641
+ );
642
+ }
643
+ ```
644
+
645
+ ## To a browser
646
+
647
+ ### writeSseEvents(response, events, options?)
648
+
649
+ ```ts
650
+ declare function writeSseEvents<E extends { type: string; seq: number }>(
651
+ response: ServerResponse,
652
+ events: AsyncIterable<E>,
653
+ options?: SseWriteOptions<E>,
654
+ ): Promise<void>;
655
+ ```
656
+
657
+ From `llm-large-files/node`. Sends events to a browser as Server-Sent Events, one message per
658
+ event:
659
+
660
+ ```text
661
+ id: 4
662
+ event: request.start
663
+ data: {"type":"request.start","requestId":"req_1",…,"seq":4,"runId":"run_3f9a0c1d2e4b5a67","time":1795374302640}
664
+
665
+ ```
666
+
667
+ `id` is the event's `seq`, `event` its `type`, and `data` the JSON of the event itself, its
668
+ envelope included, on one line (U+2028 and U+2029 are written escaped). What it does:
669
+
670
+ 1. Writes a `200` with these headers, when no headers are sent yet: `Content-Type:
671
+ text/event-stream; charset=utf-8`, `Cache-Control: no-cache, no-transform`, `Connection:
672
+ keep-alive` and `X-Accel-Buffering: no` (which tells nginx not to buffer).
673
+ 2. Writes each event as it comes, and waits whenever the client reads slower than events come.
674
+ Every `heartbeatMs` it sends a `: keep-alive` comment, which keeps proxies from closing a
675
+ quiet stream.
676
+ 3. Ends the response after the last event, unless `end: false`.
677
+
678
+ | Option | Type | Default | What it does |
679
+ |---|---|---|---|
680
+ | `heartbeatMs` | `number` | `15_000` | Milliseconds between two `: keep-alive` comments. 0 sends none. |
681
+ | `headers` | `Record<string, string \| number \| string[]>` | none | Headers to send besides the event-stream ones, or in their place: a name matches whatever its case. Used only when the headers are not sent yet. |
682
+ | `map` | `(event: E) => SseMessage \| undefined` | [`sseMessageOf`](#ssemessageofevent) | What to send for an event: `{ event?, data, id? }`, with `event` and `id` taken from the event when left out. Return `undefined` to skip the event. |
683
+ | `end` | `boolean` | `true` | `false` keeps the response open after the last event. |
684
+
685
+ **When the client goes away**, or someone else ends the response, it stops reading the events and
686
+ calls the iterator's `return()`. For an `askStream`, or another `eventStream`, passed in directly,
687
+ that stops the run at once. An async generator that wraps one (to rename or skip events) stops it
688
+ only at its next `yield`: a run waiting on a long model request goes on until then. To change what
689
+ is sent, use `map` and pass the stream itself. If you do wrap it, stop the run yourself:
690
+ `response.once("close", () => stream.abort())`.
691
+
692
+ **It resolves** when the events end or the client goes away. It rejects when the iterable or
693
+ `map` throws, after ending the response (an `eventStream` never throws: a run that fails ends with
694
+ its error event), and when the headers cannot be written (an invalid value in `headers`), after
695
+ stopping the producer and destroying the response.
696
+
697
+ ```ts
698
+ import { createServer } from "node:http";
699
+ import { askStream, createLargeFiles, FileDocumentStore } from "llm-large-files";
700
+ import { gemini, geminiApi } from "llm-large-files/gemini";
701
+ import { writeSseEvents } from "llm-large-files/node";
702
+
703
+ const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
704
+ const model = gemini(geminiApi({ apiKey: process.env.GEMINI_API_KEY!, model: "gemini-3.8-flash" }));
705
+
706
+ // Assumed: readQuestion() reads and checks the JSON body, and saveToolTurns() keeps the tool
707
+ // rounds with the chat (see the conversations guide).
708
+ createServer(async (request, response) => {
709
+ const { chatId, question, documentIds } = await readQuestion(request);
710
+ const stream = askStream({ files, model, documentIds, messages: [{ role: "user", text: question }] });
711
+ // Every event goes to the page. If the page goes away, the question stops.
712
+ await writeSseEvents(response, stream);
713
+ try {
714
+ const result = await stream.result;
715
+ saveToolTurns(chatId, result.toolTurns);
716
+ } catch (error) {
717
+ // The page saw run.error. An AbortError means it went away.
718
+ if ((error as Error).name !== "AbortError") console.error(error);
719
+ }
720
+ }).listen(3000);
721
+ ```
722
+
723
+ To skip events, or to put an error in your app's own words, use `map`:
724
+
725
+ ```ts
726
+ import { sseMessageOf, writeSseEvents } from "llm-large-files/node";
727
+
728
+ // Assumed: response and stream as above, and userMessage() turns an EventError into your app's own words, from its kind and name.
729
+ await writeSseEvents(response, stream, {
730
+ map: (event) => {
731
+ // The page does not show requests: skip them.
732
+ if (event.type === "request.start" || event.type === "request.end") return undefined;
733
+ if (event.type === "run.error") return sseMessageOf({ ...event, error: { ...event.error, message: userMessage(event.error) } });
734
+ return sseMessageOf(event);
735
+ },
736
+ });
737
+ ```
738
+
739
+ `examples/server.ts` is a whole server and page built this way, with a reader of the events in the
740
+ browser. [Web app](../guides/web-app.md) has the rest of a chat page: uploads, cancelling,
741
+ proxies.
742
+
743
+ ### sseMessageOf(event)
744
+
745
+ ```ts
746
+ declare function sseMessageOf<E extends { type: string; seq: number }>(event: E): SseMessage;
747
+
748
+ type SseMessage = { event?: string; data: unknown; id?: string | number };
749
+ ```
750
+
751
+ From `llm-large-files/node`. What `writeSseEvents` sends for an event by default: `{ event: type,
752
+ id: seq, data }`, where `data` is the event itself, `type`, `seq`, `runId` and `time` included.
753
+ Two events are made smaller:
754
+
755
+ | Event | `data` |
756
+ |---|---|
757
+ | `run.finish` | `{ type, seq, runId, time, result }`, where `result` is `{ answered, text, finishReason, blockReason, steps, evidence, turns, usage }`: not `toolTurns`, `plan`, `budget` or `lastUsage`. Keep `toolTurns` on the server, with the conversation. |
758
+ | `run.error` | `{ type, seq, runId, time, error, partial }`, where `partial` is `{ steps, evidence, usage }` of the partial result, or `undefined`. |
759
+ | Any other event | The event as it is. Ingest events too. |
760
+
761
+ ## Ingest
762
+
763
+ ### `IngestEvent`
764
+
765
+ The events of `files.ingest`, through `IngestInput.onEvent`:
766
+
767
+ | `type` | Fields | When |
768
+ |---|---|---|
769
+ | `ingest.start` | `name: string`, `format: DocumentFormat`, `bytes: number` | Always first, before the input is checked. `name` is the file name as it will be stored; `format` is what the name and type say (a text file can still become a log); `bytes` is the size of the file. |
770
+ | `ingest.progress` | `stage: IngestStage`, `done: number`, `total?: number`, `unit: "pages" \| "parts" \| "bytes" \| "characters"` | How far a stage is. `total` is absent when it is not known. See [Stages and units](#stages-and-units). |
771
+ | `ingest.finish` | `document: DocumentSummary` | Always last when the document is stored. `document` is [`toDocumentSummary(meta)`](./library.md#documentsummary): the summary an upload's `201` holds, without `owner`. |
772
+ | `ingest.error` | `error: EventError` | Always last when the ingest throws: a refusal, an abort, a store that failed, or a listener that threw. |
773
+
774
+ Each event also has `seq`, `runId` and `time`. Nothing comes after `ingest.finish` or
775
+ `ingest.error`: what an extractor of your own reports after the ingest gave up, or after it
776
+ returned, is dropped. An input that is refused at once (an empty file, an owner that is not
777
+ allowed) still sends `ingest.start` and then `ingest.error`.
778
+
779
+ ```ts
780
+ // Assumed: files is your createLargeFiles(), bytes the uploaded file, userId the signed-in user.
781
+ const meta = await files.ingest({
782
+ name: "report.pdf",
783
+ bytes,
784
+ owner: userId,
785
+ onEvent: (event) => {
786
+ if (event.type === "ingest.progress") {
787
+ console.log(`${event.stage}: ${event.done}${event.total !== undefined ? ` of ${event.total}` : ""} ${event.unit}`);
788
+ }
789
+ if (event.type === "ingest.error") console.log(`Not stored: ${event.error.message}`);
790
+ },
791
+ });
792
+ ```
793
+
794
+ ### Stages and units
795
+
796
+ `IngestStage` is one of seven stages. A file goes only through the stages that apply to it, in
797
+ this order, and each stage ends before the next starts:
798
+
799
+ | Stage | Unit | `total` | What it counts | When |
800
+ |---|---|---|---|---|
801
+ | `"check"` | pages | the pages | Pages checked before their text is read. | A PDF, with `@cantoo/pdf-lib` installed and `checkPages` on. |
802
+ | `"extract"` | pages, or parts | the pages, or the parts | Text read: each page of a PDF; each part of a DOCX (body, footnotes, headers…), each slide of a PPTX or each sheet of an XLSX. | A PDF, DOCX, PPTX or XLSX, or an extractor of your own that reports it. Not a text file. |
803
+ | `"pictures"` | pages | the pages | Pages looked at for pictures. | A PDF, with `@cantoo/pdf-lib` installed and `pictures` on. |
804
+ | `"decode"` | bytes | the bytes | One event when the file is decoded. | A text file that is not UTF-8, and every HTML file. |
805
+ | `"prepare"` | characters | the characters | The text cleaned before it is cut into lines. | Every file. |
806
+ | `"index"` | characters | the characters | The line index built. | A store with `putIndex`, such as `FileDocumentStore`. |
807
+ | `"store"` | parts | the writes | Each write to the store, once done: the original file (`keepOriginals`), the line index, then the text. | Every file. |
808
+
809
+ So with `FileDocumentStore` and `@cantoo/pdf-lib`, a PDF goes through `check`, `extract`,
810
+ `pictures`, `prepare`, `index` and `store`, and a UTF-8 log through `prepare`, `index` and
811
+ `store`. Measuring the text, the outline and the log profile
812
+ report nothing: they are quick.
813
+
814
+ **Throttling.** Each stage sends at most one `ingest.progress` every 12 ms, however stages take
815
+ turns. A progress that completes its stage (`done` reaches `total`) goes out at once. When the
816
+ stages end, the last progress of each that was held back goes out, in the order they began. So
817
+ the last progress of a stage always has its final `done`, which equals `total` when `total` is
818
+ known. A stage with nothing to report may send none. The events cost nothing when no one listens:
819
+ without `onEvent`, no progress is worked out.
820
+
821
+ ### Uploads with progress
822
+
823
+ `createDocumentHandlers(files).upload`, from `llm-large-files/node`, answers with the ingest's
824
+ events when the request's `Accept` header names `text/event-stream` itself: not with `q=0`, and
825
+ not only through a wildcard such as `*/*` or `text/*`.
826
+
827
+ 1. The checks that answer with an HTTP error come first, as before, in JSON: a missing name
828
+ (`400`), an owner that `getOwner` refused or that is not allowed (its status, or `500`), a body
829
+ another middleware already parsed (`400`), and a file larger than `maxUploadBytes` (`413`).
830
+ 2. Then it answers `200` with Server-Sent Events, written by `writeSseEvents`: `ingest.start`,
831
+ `ingest.progress`…, and last one of:
832
+ - `ingest.finish`, whose `document` is the summary a `201` would hold;
833
+ - `ingest.error`, whose `error` is `{ message, status }`, the message and status a JSON answer
834
+ would have: `422` with the reason for a file that cannot be read ("empty.txt is empty."),
835
+ `500` "Upload failed." for a store that failed, and so on, as in the
836
+ [node reference](./node.md#uploadrequest-response). For a file that could not be read, it also
837
+ has `code`, the `IngestError` code (`"empty"`, `"busy"`…; new in 0.8.0).
838
+ 3. When the client goes away, the ingest stops and nothing is stored.
839
+
840
+ It always ends with `ingest.finish` or `ingest.error`, even with a `LargeFiles` of your own whose
841
+ `ingest` sends no events: then that one event is all there is, with `seq` 1. Without the header,
842
+ `upload` answers `201` with JSON, as in 0.6.0.
843
+
844
+ In the browser, read the answer as a stream. The `data` of each message is the event itself:
845
+
846
+ ```ts
847
+ import type { DocumentSummary, IngestEvent } from "llm-large-files";
848
+
849
+ /** Uploads a file and reports its progress. Resolves with the summary a 201 would hold. */
850
+ export async function upload(file: File, onProgress: (line: string) => void): Promise<DocumentSummary> {
851
+ const response = await fetch("/api/documents", {
852
+ method: "POST",
853
+ body: file,
854
+ headers: { "Content-Type": "application/octet-stream", "X-File-Name": encodeURIComponent(file.name), Accept: "text/event-stream" },
855
+ });
856
+ // A missing name, a refused owner or a file too large still get an HTTP error in JSON.
857
+ if (!response.ok) throw new Error((await response.json()).error);
858
+ const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();
859
+ let buffer = "";
860
+ for (;;) {
861
+ const { value, done } = await reader.read();
862
+ if (done) throw new Error("The upload ended without an answer.");
863
+ buffer += value;
864
+ let end: number;
865
+ while ((end = buffer.indexOf("\n\n")) >= 0) {
866
+ const block = buffer.slice(0, end);
867
+ buffer = buffer.slice(end + 2);
868
+ const data = block.split("\n").filter((line) => line.startsWith("data: ")).map((line) => line.slice(6)).join("\n");
869
+ if (!data) continue; // a keep-alive comment
870
+ const event = JSON.parse(data) as IngestEvent;
871
+ if (event.type === "ingest.progress") onProgress(`${event.stage}: ${event.done}${event.total !== undefined ? ` of ${event.total}` : ""} ${event.unit}`);
872
+ if (event.type === "ingest.finish") return event.document;
873
+ if (event.type === "ingest.error") throw new Error(event.error.message);
874
+ }
875
+ }
876
+ }
877
+ ```
878
+
879
+ ### `ExtractInput.onProgress`, for an extractor of your own
880
+
881
+ An [extractor](./library.md#extractor) gets `onProgress` in its [`ExtractInput`](./library.md#extractinput) when someone listens
882
+ to the ingest's events. Call it as the extraction goes on, and the ingest reports it as
883
+ `ingest.progress`. An extractor that never calls it works as before: its file has no `extract`
884
+ progress. New in 0.7.0.
885
+
886
+ ```ts
887
+ type ExtractProgress = {
888
+ stage?: "extract" | "check" | "pictures" | "decode";
889
+ done: number;
890
+ total?: number;
891
+ unit: "pages" | "parts" | "bytes";
892
+ };
893
+ ```
894
+
895
+ | Field | Type | Default | What it does |
896
+ |---|---|---|---|
897
+ | `stage` | `"extract" \| "check" \| "pictures" \| "decode"` | `"extract"` | The stage it counts. |
898
+ | `done` | `number` | required | How many are done: a finite number from 0. |
899
+ | `total` | `number` | unknown | How many there are, when you know. |
900
+ | `unit` | `"pages" \| "parts" \| "bytes"` | required | What `done` and `total` count. |
901
+
902
+ A report that does not fit (another stage or unit, a `done` that is negative or not a number) is
903
+ left out, and a `total` that is not a number counts as unknown. Reports after the extractor
904
+ returned are dropped. Call it as often as you like: the ingest sends at most one event every
905
+ 12 ms for each stage, and the last one. A throw from it is the listener's error: let it pass, so
906
+ that the ingest ends with it.
907
+
908
+ ```ts
909
+ import { createLargeFiles, MemoryDocumentStore, type Extractor } from "llm-large-files";
910
+
911
+ // Assumed: splitPages() cuts a scanned PDF into page images, and recognize() is your OCR service.
912
+ const scannedPdf: Extractor = async (bytes, input) => {
913
+ const pages = await splitPages(bytes);
914
+ const texts: string[] = [];
915
+ for (const [index, page] of pages.entries()) {
916
+ texts.push(await recognize(page, input.signal));
917
+ input.onProgress?.({ done: index + 1, total: pages.length, unit: "pages" });
918
+ }
919
+ return { text: texts.map((text, index) => `--- Page ${index + 1} ---\n${text}`).join("\n\n"), pages: pages.length };
920
+ };
921
+
922
+ export const files = createLargeFiles({ store: new MemoryDocumentStore(), extractors: { pdf: scannedPdf } });
923
+ ```
924
+
925
+ [`ExtractProgress`](./library.md#extractprogress) is in the library reference too, and
926
+ [Custom extractors](../guides/pdfs.md#custom-extractors) has more on extractors of your own and
927
+ OCR.
928
+
929
+ ## Your own loop
930
+
931
+ ### `ToolCallHooks`
932
+
933
+ When you run the tools in a loop of your own, [`ToolSet.executeWithFiles`](./tools.md#toolset) takes the listeners of one
934
+ call as an optional fourth argument. With them, the progress and the model requests of two
935
+ whole-file reads that run at once can be told apart. `askWithFiles` uses them for its events.
936
+ New in 0.7.0.
937
+
938
+ ```ts
939
+ executeWithFiles(name: string, args: Record<string, unknown>, limits?: ToolCallLimits, hooks?: ToolCallHooks): Promise<ToolOutput>;
940
+
941
+ type ToolCallHooks = {
942
+ onProgress?: ProgressListener;
943
+ onRequest?: (request: ToolRequestStart) => ToolRequestHandle;
944
+ };
945
+ type ToolRequestStart = { purpose: "part" | "merge" | "final"; detail: string };
946
+ type ToolRequestHandle = {
947
+ retry(notice: { attempt: number; delayMs: number; error: unknown }): void;
948
+ end(end: ToolRequestEnd): void;
949
+ };
950
+ type ToolRequestEnd = { outcome: "ok" | "error"; usage?: GenerateUsage; error?: unknown };
951
+ ```
952
+
953
+ | Field | Type | What it does |
954
+ |---|---|---|
955
+ | `onProgress` | `ProgressListener` | Progress of this call, in place of `ToolOptions.onProgress` for it: `{ kind: "map" \| "reduce", message, done, total }`. |
956
+ | `onRequest` | `(request: ToolRequestStart) => ToolRequestHandle` | Called as each model request of this call starts, with its `purpose` and `detail` (`"part 3 of 12"`, `"first half of part 3 of 12"`, `"round 2: 1 of 4"`, `"the answer"`). The handle you return is told of each retry of that request, and once of its end, with the usage its part reader reported (summed over its sends) and, on an error, the error. |
957
+
958
+ Only `analyze_whole_document` uses them; the other tools ignore them, and `view_pages` too.
959
+ `execute()` takes no hooks. A `ToolSet` of your own may take the fourth argument and ignore it;
960
+ code that implements `ToolSet` for 0.6.0 still compiles. Do not throw from the hooks: a throw
961
+ becomes a failed part, or the tool's error result, as a throw of `ToolOptions.onProgress` does.
962
+ The `error` given to `end` is the provider's own: do not send it to a browser as it is.
963
+
964
+ ```ts
965
+ import type { ToolCallHooks } from "llm-large-files";
966
+
967
+ // Assumed: files, model and documentIds as in your loop, and call is one ToolCall of the model's reply.
968
+ const context = await files.prepare(documentIds, { tokens: 1_000, bytes: 4_000 });
969
+ const tools = files.tools(context.plan.searchable, { generate: model.generateText });
970
+
971
+ // The listeners of one call: two whole-file reads that run at once report apart.
972
+ const hooks: ToolCallHooks = {
973
+ onProgress: (progress) => console.log(call.id, `${progress.message}…`),
974
+ onRequest: (start) => {
975
+ const began = Date.now();
976
+ console.log(call.id, "request", start.purpose, start.detail);
977
+ return {
978
+ retry: ({ attempt, delayMs }) => console.log(call.id, `retry ${attempt} in ${delayMs} ms`),
979
+ end: ({ outcome, usage }) => console.log(call.id, start.detail, outcome, `${Date.now() - began} ms`, usage?.inputTokens ?? 0),
980
+ };
981
+ },
982
+ };
983
+ const output = await tools.executeWithFiles(call.name, call.args, {}, hooks);
984
+ ```
985
+
986
+ [Your own adapter and loop](../guides/own-adapter-and-loop.md) explains the rest of such a loop.
987
+
988
+ ## Related
989
+
990
+ - [The tool loop](./ask.md): `askWithFiles`, `AskOptions` (`onText`, `onActivity`, `onStep`),
991
+ `AskResult`, `Evidence`, `partialResultOf`.
992
+ - [`llm-large-files/node`](./node.md): `createDocumentHandlers` and every status and body of an
993
+ upload.
994
+ - [The library](./library.md): `IngestInput`, `DocumentSummary`, extractors.
995
+ - [Tools](./tools.md): each tool, its arguments and results, `ToolSet`.
996
+ - [`llm-large-files/gemini`](./gemini.md): `askGemini` and its options.
997
+
998
+ Related guides: [Web app](../guides/web-app.md) for a chat page that streams answers and uploads,
999
+ [Errors and reliability](../guides/errors-and-reliability.md) for what each error kind means and
1000
+ what to show, and [Conversations](../guides/conversations.md) for keeping `toolTurns` with the
1001
+ chat.