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,1590 @@
1
+ # Web app
2
+
3
+ This guide is for you if you add large files to a web chat: the browser uploads files, your server
4
+ keeps them and asks the model, and the answer streams back to the page with its progress. It covers
5
+ uploads with `createDocumentHandlers` or with a route of your own, the browser side of an upload
6
+ with its progress, a Server-Sent Events route that streams the question's events, cancelling, and
7
+ reading the stream in the browser. The samples use Express 5 and Gemini on Vertex AI. The approach
8
+ depends on neither: with Express 4, catch errors in async routes yourself, and with another model,
9
+ call `askStream` (see the end of [the chat route](#a-server-sent-events-route)).
10
+
11
+ ## What you build
12
+
13
+ Three routes. Their paths are yours: the library mounts none.
14
+
15
+ | Route | What it does | With |
16
+ |---|---|---|
17
+ | `POST /api/documents` | Takes one file, extracts and stores its text, and answers with a `DocumentSummary`, or with its progress and then the summary as Server-Sent Events. | `createDocumentHandlers(files).upload`, or `files.ingest` in a route of your own |
18
+ | `GET` and `DELETE /api/documents/:id` | Looks a document up, or deletes it. | `get` and `remove` of the same handlers |
19
+ | `POST /api/chat` | Asks the model about the chat's documents, and streams the question's events as Server-Sent Events: the tool calls, the answer, the result. | `writeSseEvents` with `askStream`, or with `eventStream` over `askGemini` |
20
+
21
+ The ID an upload returns belongs to the chat session, not to one message: keep it with the session,
22
+ and pass every document of the session on every question. A runnable server with uploads, a
23
+ streamed chat route and a page is in the repository: see
24
+ [the example server](#the-example-server-examplesserverts).
25
+
26
+ The samples import `files` and `endpoint` from one module, created once per process:
27
+
28
+ ```ts
29
+ // large-files.ts
30
+ import { GoogleAuth } from "google-auth-library";
31
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
32
+ import { vertexAi } from "llm-large-files/gemini";
33
+
34
+ export const files = createLargeFiles({
35
+ store: new FileDocumentStore(process.env.LARGE_FILES_DIR ?? "./data/large-files"),
36
+ });
37
+
38
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
39
+ export const endpoint = vertexAi({
40
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
41
+ model: "gemini-3.8-flash",
42
+ accessToken: async () => (await auth.getAccessToken())!,
43
+ });
44
+
45
+ // An expired document is ignored at once. This frees the space it took.
46
+ setInterval(() => {
47
+ files.sweep().catch((error) => console.error("sweep failed", error));
48
+ }, 60 * 60 * 1000).unref();
49
+ ```
50
+
51
+ Uploads are taken up to 100 MB (`maxUploadBytes`) and kept for 72 hours (`ttlMs`). Every option
52
+ is in the [library reference](../reference/library.md#largefilesoptions); where the documents live,
53
+ and a layout per user and per chat session, are in [Storage](./storage.md).
54
+
55
+ ## Uploads with `createDocumentHandlers`
56
+
57
+ `createDocumentHandlers(files, options)` from `llm-large-files/node` returns three handlers that
58
+ take Node's `IncomingMessage` and `ServerResponse`. Each answers with JSON itself, errors included,
59
+ and never rejects, so you can call it without a `catch`, from `node:http` or from Express 4 or 5.
60
+
61
+ | Handler | Route it for | What it does |
62
+ |---|---|---|
63
+ | `upload(request, response)` | `POST` | Asks `getOwner` who is asking, reads the raw body up to `files.maxUploadBytes`, ingests it with that owner, and answers `201` with the document's summary. |
64
+ | `get(request, response, id)` | `GET` | Answers `200` with the summary, or `404` when the document is unknown, expired, deleted, or another owner's. |
65
+ | `remove(request, response, id)` | `DELETE` | Deletes the document, its text and any kept original, and answers `200` with `{ "deleted": true }`, or `{ "deleted": false }` when this owner had no such document. |
66
+
67
+ The handlers do not check the method or the path. Route each request to the one you mean.
68
+
69
+ ### Mount them in Express
70
+
71
+ ```ts
72
+ // server.ts
73
+ import express from "express";
74
+ import { createDocumentHandlers } from "llm-large-files/node";
75
+ import { files } from "./large-files.js";
76
+
77
+ export const app = express();
78
+ // Your auth middleware goes first. currentUserId(request) stands for it: the signed-in user's ID, or undefined.
79
+
80
+ const documents = createDocumentHandlers(files, {
81
+ // Uploads become this user's: no other user can read or delete them.
82
+ getOwner: (request) => {
83
+ const userId = currentUserId(request);
84
+ if (!userId) throw Object.assign(new Error("Sign in to attach files."), { status: 401 });
85
+ return userId;
86
+ },
87
+ });
88
+
89
+ // Before any body parser: the body of an upload is the raw file.
90
+ app.post("/api/documents", documents.upload);
91
+ app.get("/api/documents/:id", (req, res) => documents.get(req, res, req.params.id));
92
+ app.delete("/api/documents/:id", (req, res) => documents.remove(req, res, req.params.id));
93
+ app.use(express.json());
94
+ ```
95
+
96
+ `upload` reads the request body itself. A body parser that runs before it changes what it finds:
97
+
98
+ - **A `Buffer` in `request.body`**, as `express.raw()` leaves it, is used as the file, with the
99
+ same size limit.
100
+ - **An object with fields in `request.body`**, as `express.json()` leaves it for a JSON request, is
101
+ refused with `400`: "The upload body was already parsed by another middleware. Mount the upload
102
+ route before body parsers, or send Content-Type: application/octet-stream."
103
+ - **A stream another parser has read and left nothing usable** reads as an empty file: `422`,
104
+ "app.log is empty."
105
+
106
+ Mount the upload route before your body parsers, and have the browser send
107
+ `Content-Type: application/octet-stream`, which JSON and form parsers leave alone.
108
+
109
+ ### Mount them in plain `node:http`
110
+
111
+ ```ts
112
+ import { createServer } from "node:http";
113
+ import { createDocumentHandlers } from "llm-large-files/node";
114
+ import { files } from "./large-files.js";
115
+
116
+ // currentUserId(request) stands for your auth, as above.
117
+ const documents = createDocumentHandlers(files, { getOwner: (request) => currentUserId(request) });
118
+
119
+ createServer((request, response) => {
120
+ const { pathname } = new URL(request.url ?? "/", "http://localhost");
121
+ const match = /^\/api\/documents(?:\/([^/]+))?$/.exec(pathname);
122
+ if (match) {
123
+ const id: string | undefined = match[1];
124
+ if (request.method === "POST" && id === undefined) return void documents.upload(request, response);
125
+ if (request.method === "GET" && id !== undefined) return void documents.get(request, response, id);
126
+ if (request.method === "DELETE" && id !== undefined) return void documents.remove(request, response, id);
127
+ }
128
+ response.writeHead(404).end();
129
+ }).listen(3000);
130
+ ```
131
+
132
+ The handlers work wherever you can reach Node's request and response objects, as long as the
133
+ framework has not read the body of the upload first and does not send a reply of its own. Other
134
+ frameworks need a step for that. These are not tested in this repository:
135
+
136
+ - **Next.js API routes** (the Pages Router, on the Node runtime):
137
+ `export const config = { api: { bodyParser: false } }`, or Next.js reads the body first and the
138
+ upload reads as empty.
139
+ - **Fastify**: add a content-type parser for `application/octet-stream` that leaves the body unread
140
+ (Fastify refuses that type with `415` otherwise), and call `reply.hijack()` before you pass
141
+ `request.raw` and `reply.raw`.
142
+ - **Koa**: set `ctx.respond = false` and pass `ctx.req` and `ctx.res`.
143
+
144
+ A framework that gives you only the Fetch API's `Request` and `Response` needs a route of its own:
145
+ [see below](#fetch-api-request-and-response).
146
+
147
+ ### Who owns an upload: `getOwner`
148
+
149
+ `getOwner(request)` returns the owner of the request: a string, `undefined`, or a promise of
150
+ either. The handlers call it before they read the body, so a refused upload is never buffered.
151
+
152
+ - **A user ID.** The upload is ingested with that owner, and `get` and `remove` pass it on. A
153
+ document of another owner answers exactly as one that does not exist: `404`, or
154
+ `{ "deleted": false }`.
155
+ - **`undefined`.** The request is anonymous, and the upload has no owner: anyone who has its ID can
156
+ read it, delete it and ask about it. Use this only for a demo.
157
+ - **An empty owner** (`""`, spaces only, or `null` from JavaScript) is the server's mistake, since
158
+ it would be one owner shared by every caller without a user. The upload is answered `500`
159
+ `{ "error": "Upload failed (empty owner)." }` before its body is read. An owner that is neither a
160
+ string nor a finite number (`req.user` in place of `req.user.id`, say) is answered
161
+ `{ "error": "Upload failed (owner is not a string)." }`. `get` and `remove` pass such an owner on
162
+ as before. Where every upload needs a user, throw an error with `status: 401` when there is
163
+ none, as the example above does. Return `undefined` only where anonymous uploads are meant, and
164
+ write `user?.id || undefined` there, not `user?.id ?? ""`: a header that arrives empty gives `""`
165
+ too.
166
+ - **A thrown error with a `status` (or `statusCode`) from 400 to 599**, as the `http-errors`
167
+ package makes them: the handler answers with that status and the error's message, as the `401`
168
+ above. Any other error is answered `500`, without its message, which may name your hosts.
169
+
170
+ The owner is one opaque string, compared as it is. Pass the same string as `owner` to `askGemini`
171
+ or `askWithFiles`, and to `files.getMeta`, `files.getOriginal` and `files.delete`. An owner per
172
+ chat session (for example `${userId}/${sessionId}`) works the same way, with `getOwner` reading the
173
+ session from the request: see [Storage](./storage.md), and [Security](../security.md) for what
174
+ ownership does and does not protect.
175
+
176
+ ### What the browser sends
177
+
178
+ - **The body is the file**, as raw bytes, not a form.
179
+ - **`X-File-Name`** names it, URI-encoded with `encodeURIComponent`, so that any name survives an
180
+ HTTP header. A `?name=` query parameter works too. One of them is required. The library keeps the
181
+ last path segment of the name, up to 255 characters and never half of one. Control characters,
182
+ line and paragraph separators and text-direction controls become a space, and most characters
183
+ that show nothing are removed (variation selectors and joiners stay): the name is shown to the
184
+ model and in your UI.
185
+ - **`X-File-Type`** is the MIME type, and is optional. Without it, `Content-Type` is taken, unless
186
+ it is `application/octet-stream`. The format comes from the extension first (`.log`, `.md`,
187
+ `.json`, `.csv`, `.pdf`, `.docx`, `.pptx` and a few more), then from the MIME type; anything else
188
+ is text, and text that looks like a log becomes a log. A text file needs no charset: one that is
189
+ not UTF-8 is read in the older encoding of Hebrew, Arabic, Cyrillic, Japanese or Western European
190
+ text that its letters fit, or as UTF-8 with the characters that are not valid counted. None is
191
+ refused for its encoding ([Text encodings](./pdfs.md#text-encodings)).
192
+ - **`Content-Type: application/octet-stream`**, so that no body parser takes the upload.
193
+
194
+ [Upload from the browser](#upload-from-the-browser) has the `fetch` call.
195
+
196
+ ### What it answers
197
+
198
+ A successful upload answers `201` with a `DocumentSummary`:
199
+
200
+ ```json
201
+ { "id": "doc_3f9c0a7e5b2d4c18a6e0f7b9d1c3e5a7", "name": "app.log", "mimeType": "text/plain",
202
+ "format": "log", "bytes": 5082044, "lines": 60000, "estimatedTokens": 1270511,
203
+ "expiresAt": "2026-11-22T07:43:14.435Z" }
204
+ ```
205
+
206
+ `pages` is there too for a PDF, a PPTX or an XLSX (its sheets). For a text file that was not valid
207
+ UTF-8, `encoding` names the older encoding it was read in (`"windows-1255"`), and
208
+ `replacedCharacters` counts the characters stored as � ([Text encodings](./pdfs.md#text-encodings)).
209
+ Your page can show "read as windows-1255", or warn that some characters could not be read and ask
210
+ for the file saved as UTF-8.
211
+
212
+ Everything else is JSON `{ "error": "…" }`, with a message you can show: `400` for a missing name or
213
+ a body another middleware already parsed, `413` over `maxUploadBytes`, `422` for a file that cannot
214
+ be read, an error's own status (400 to 599) from `getOwner`, an extractor or your store, and `500`
215
+ for a failure of the server, among them `Upload failed (empty owner).` and
216
+ `Upload failed (owner is not a string).` ([above](#who-owns-an-upload-getowner)). `get` answers
217
+ `404` for a document this owner cannot see, and `get` and `remove` answer `500` when the store
218
+ cannot be read. Every status and body is in the
219
+ [node reference](../reference/node.md#uploadrequest-response).
220
+
221
+ A store of your own that fails while it writes an upload can throw an error with a `status` (or
222
+ `statusCode`) from 400 to 599 (a `503`, say): the handler answers with that status and the error's
223
+ message. A Node system error, with `code` and `syscall`, is answered `500` with its code. Any other
224
+ error it throws is answered `500` "Upload failed.", without its message, which may name your hosts.
225
+ The handlers log nothing: log the error in your store before you throw it. Behind an `ingest` of
226
+ your own that throws a new error in the store's place, as `ingestInProcess` in
227
+ [Deployment](./deployment.md#uploads-and-ingest) does, the handler answers `422` with that error's
228
+ message, the store's own, unless the error keeps a status, or a code and a syscall. See
229
+ [Storage](./storage.md#errors).
230
+
231
+ ## Uploads through your own route
232
+
233
+ `upload` writes the response itself. Ingest the file in a route of your own when:
234
+
235
+ - the browser sends a `multipart/form-data` form;
236
+ - your server must record the new document in the chat session as it is uploaded;
237
+ - your framework gives you the Fetch API's `Request` and `Response`, not Node's objects;
238
+ - reading the file takes long enough that the user should not wait on the request (OCR of a long
239
+ scan, for example).
240
+
241
+ ### `files.ingest` and its errors
242
+
243
+ `files.ingest(input)` extracts, profiles and stores one file, and returns its `DocumentMeta`. Its
244
+ input, an [`IngestInput`](../reference/library.md#ingestinput):
245
+
246
+ | Field | What it is |
247
+ |---|---|
248
+ | `name` | The file's name. Cleaned as above. |
249
+ | `mimeType` | Optional. Used for the format when the extension says nothing. |
250
+ | `bytes` | The file, as a `Uint8Array`. A Node `Buffer` is one. |
251
+ | `owner` | Optional. The user (or tenant, or chat session) the document belongs to. Every later call must pass the same. A string that is not empty or only spaces: `""` and `null` throw a `TypeError` ([Storage](./storage.md#how-ownership-works)). Check it before you read the upload, as the handler does: the helper below would answer that error `422`. |
252
+ | `signal` | Optional. Stops the ingest when it aborts, for example when the uploader goes away: `ingest` throws its `reason`, and nothing is stored. |
253
+
254
+ Answer the browser with `toDocumentSummary(meta)`, not with `meta`: the summary holds the fields that
255
+ are safe to return to a browser, while `meta` also holds the owner, the outline and the log profile.
256
+
257
+ `ingest` throws an [`IngestError`](../reference/library.md#ingesterror) (a plain `Error` until
258
+ 0.8.0), with a message written for the user and a `code`, when it cannot take the file:
259
+ the cases of the `422` above (an empty, binary or compressed file, no text, a missing optional
260
+ dependency, a file past `maxTextBytes` or `maxPdfPages`, one that took longer than
261
+ `ingestTimeoutMs`), and a file larger than `maxUploadBytes` ("app.log is larger than the 100 MB
262
+ upload limit."). [PDFs and other formats](./pdfs.md#what-is-refused) lists every message. A store
263
+ that fails while it writes throws its own error, as it came. This helper tells them apart by the
264
+ rule `createDocumentHandlers` uses, with two differences, given below the code:
265
+
266
+ ```ts
267
+ // ingest-failure.ts
268
+ /**
269
+ * The status and message for an error of files.ingest, by the rule of createDocumentHandlers: an
270
+ * error with a status (or statusCode) keeps it; a Node system error is the server's 500, which
271
+ * names only its code; a value that is not an Error is the server's 500 too; anything else is a
272
+ * file that cannot be read, whose message is written for the user. Unlike the handler, it answers
273
+ * a store's write error that has no status and no system error code with 422 and its message.
274
+ */
275
+ export function ingestFailure(error: unknown): { status: number; error: string } {
276
+ const { status, statusCode, code, syscall } = (error ?? {}) as { status?: unknown; statusCode?: unknown; code?: unknown; syscall?: unknown };
277
+ const value = typeof status === "number" ? status : statusCode;
278
+ if (error instanceof Error && typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599) {
279
+ return { status: value, error: error.message || "Upload failed." };
280
+ }
281
+ if (typeof code === "string" && typeof syscall === "string") return { status: 500, error: `Upload failed (${code}).` };
282
+ if (!(error instanceof Error)) return { status: 500, error: "Upload failed." };
283
+ return { status: 422, error: error.message };
284
+ }
285
+ ```
286
+
287
+ The first difference is a store's write error with no status and no system error code. The
288
+ handler knows it by a mark that `ingest` keeps, and answers it `500` "Upload failed.", without the
289
+ store's message. The package does not export the mark, so this helper answers it `422` with the
290
+ store's own message, and the routes below send that message to the browser: it may name your hosts.
291
+ Give your store's write errors a status and a message of your own ([Storage](./storage.md#errors)),
292
+ and the handler and this helper answer them alike, except for the second difference. That one is a
293
+ status of `413`: the handler answers it with its upload-limit message ("The file is larger than the
294
+ 100 MB upload limit."), and this helper with the error's own message.
295
+
296
+ Check the size before you call `ingest`, and refuse with `413` while you read: `ingest` checks it
297
+ too, but only once the whole file is in memory.
298
+
299
+ ### Multipart forms
300
+
301
+ Any multipart parser works: read the one file into memory, up to `files.maxUploadBytes`, and pass
302
+ its bytes, name and type to `ingest`. This sketch uses `busboy`, and records the document in the
303
+ chat session as part of the upload:
304
+
305
+ ```ts
306
+ // upload-form.ts
307
+ import busboy from "busboy";
308
+ import type { Request, Response } from "express";
309
+ import type { IncomingMessage } from "node:http";
310
+ import { toDocumentSummary, type DocumentMeta } from "llm-large-files";
311
+ import { ingestFailure } from "./ingest-failure.js";
312
+ import { files } from "./large-files.js";
313
+
314
+ type FormFile = { name: string; mimeType: string; bytes: Uint8Array };
315
+
316
+ class FormError extends Error {
317
+ constructor(readonly status: number, message: string) {
318
+ super(message);
319
+ }
320
+ }
321
+
322
+ /** The one file of a multipart/form-data request, read up to the upload limit. */
323
+ function readFormFile(request: IncomingMessage): Promise<FormFile> {
324
+ const limit = files.maxUploadBytes;
325
+ return new Promise((resolve, reject) => {
326
+ // busboy throws, and the promise rejects, when the request is not multipart/form-data.
327
+ const form = busboy({ headers: request.headers, defParamCharset: "utf8", limits: { files: 1, fileSize: limit + 1 } });
328
+ let file: FormFile | undefined;
329
+ let size = 0;
330
+ form.on("file", (_field, stream, info) => {
331
+ const chunks: Buffer[] = [];
332
+ stream.on("data", (chunk: Buffer) => {
333
+ size += chunk.length;
334
+ if (size <= limit) chunks.push(chunk);
335
+ });
336
+ stream.on("end", () => {
337
+ // filename is undefined when the form sent the part without one.
338
+ file = { name: info.filename ?? "upload", mimeType: info.mimeType, bytes: Buffer.concat(chunks) };
339
+ });
340
+ });
341
+ form.on("close", () => {
342
+ if (!file) reject(new FormError(400, "Attach a file."));
343
+ else if (size > limit) reject(new FormError(413, "The file is larger than the upload limit."));
344
+ else resolve(file);
345
+ });
346
+ form.on("error", reject);
347
+ request.pipe(form);
348
+ });
349
+ }
350
+
351
+ /**
352
+ * POST /api/chats/:sessionId/documents. addDocument is your app's: it checks that the chat is the
353
+ * user's and records the document ID in it.
354
+ */
355
+ export function formUploadRoute(addDocument: (sessionId: string, userId: string, documentId: string) => Promise<void>) {
356
+ return async (req: Request<{ sessionId: string }>, res: Response): Promise<void> => {
357
+ // Who is asking comes first, so a refused upload is not read.
358
+ const userId = currentUserId(req);
359
+ if (!userId) return void res.status(401).json({ error: "Sign in to attach files." });
360
+
361
+ let file: FormFile;
362
+ try {
363
+ file = await readFormFile(req);
364
+ } catch (error) {
365
+ const failure = error instanceof FormError ? error : new FormError(400, "Send the file as multipart/form-data.");
366
+ return void res.status(failure.status).json({ error: failure.message });
367
+ }
368
+
369
+ let meta: DocumentMeta;
370
+ try {
371
+ meta = await files.ingest({ ...file, owner: userId });
372
+ } catch (error) {
373
+ const failure = ingestFailure(error);
374
+ return void res.status(failure.status).json({ error: failure.error });
375
+ }
376
+
377
+ try {
378
+ await addDocument(req.params.sessionId, userId, meta.id);
379
+ } catch (error) {
380
+ // A document that is in no chat is of no use: remove it now rather than when it expires.
381
+ await files.delete(meta.id, { owner: userId }).catch(() => undefined);
382
+ throw error; // Express 5 passes it to your error handler: a 500.
383
+ }
384
+ res.status(201).json(toDocumentSummary(meta));
385
+ };
386
+ }
387
+ ```
388
+
389
+ - `defParamCharset: "utf8"` reads file names that are not ASCII (Hebrew, Chinese) as the browser
390
+ sent them. busboy's own default is Latin-1.
391
+ - `fileSize: limit + 1` makes busboy cut the file one byte past the limit, which is how the size
392
+ check knows it was larger. busboy reads the rest of the body and drops it.
393
+ - With `formidable` or `multer`, the shape is the same: let the parser enforce the size, then read
394
+ the file's bytes, name and type into `ingest`. A parser that writes the file to disk first costs
395
+ a write and a read for each upload, which `ingest` does not need.
396
+
397
+ ### Fetch API `Request` and `Response`
398
+
399
+ Next.js App Router route handlers, and other frameworks built on the Fetch API, hand you a Web
400
+ `Request`. This route takes the same raw upload as `createDocumentHandlers`, so the browser code
401
+ below works with either:
402
+
403
+ ```ts
404
+ // upload-route.ts. In the Next.js App Router, call it from app/api/documents/route.ts, on the Node
405
+ // runtime (below). ingestFailure is the helper above.
406
+ import { toDocumentSummary } from "llm-large-files";
407
+ import { ingestFailure } from "./ingest-failure.js";
408
+ import { files } from "./large-files.js";
409
+
410
+ /** A raw upload, named by its X-File-Name header, for the user `owner`. */
411
+ export async function uploadFromRequest(request: Request, owner: string): Promise<Response> {
412
+ const sent = request.headers.get("x-file-name") ?? "";
413
+ let name = sent;
414
+ try {
415
+ name = decodeURIComponent(sent);
416
+ } catch {
417
+ // Not URI-encoded: keep it as it came.
418
+ }
419
+ if (!name.trim()) return Response.json({ error: "Name the file with an X-File-Name header." }, { status: 400 });
420
+
421
+ const tooLarge = { error: "The file is larger than the upload limit." };
422
+ if (Number(request.headers.get("content-length")) > files.maxUploadBytes) return Response.json(tooLarge, { status: 413 });
423
+ const bytes = new Uint8Array(await request.arrayBuffer());
424
+ if (bytes.byteLength > files.maxUploadBytes) return Response.json(tooLarge, { status: 413 });
425
+
426
+ try {
427
+ const contentType = request.headers.get("content-type") ?? "";
428
+ const mimeType = request.headers.get("x-file-type") || (contentType.startsWith("application/octet-stream") ? "" : contentType);
429
+ const meta = await files.ingest({ name, bytes, owner, ...(mimeType ? { mimeType } : {}) });
430
+ return Response.json(toDocumentSummary(meta), { status: 201 });
431
+ } catch (error) {
432
+ const failure = ingestFailure(error);
433
+ return Response.json({ error: failure.error }, { status: failure.status });
434
+ }
435
+ }
436
+ ```
437
+
438
+ The route itself is a `POST` function in `route.ts`:
439
+
440
+ ```ts
441
+ // app/api/documents/route.ts
442
+ import { uploadFromRequest } from "../../../upload-route.js";
443
+
444
+ export const runtime = "nodejs";
445
+
446
+ export async function POST(request: Request): Promise<Response> {
447
+ const owner = await currentUserId(request); // your auth: the signed-in user's ID, or undefined
448
+ if (!owner) return Response.json({ error: "Sign in to attach files." }, { status: 401 });
449
+ return uploadFromRequest(request, owner);
450
+ }
451
+ ```
452
+
453
+ `request.arrayBuffer()` reads the whole body before you can count it, so a request without
454
+ `Content-Length` is held in memory up to whatever your framework or proxy allows. Set a body limit
455
+ there too.
456
+
457
+ The library is written for Node: it imports `node:crypto` and `node:fs`, and uses `Buffer`. Run the
458
+ route on the Node runtime; edge runtimes, such as the Next.js Edge runtime, are not supported.
459
+
460
+ ### Long ingests in the background
461
+
462
+ `ingest` runs while the upload request waits: extraction, profiling, the line index, the store's
463
+ writes. That takes seconds for most files. For work that can take minutes, such as OCR of a long
464
+ scan ([PDFs](./pdfs.md)), answer at once and ingest afterwards, and raise `ingestTimeoutMs`
465
+ (2 minutes by default) above what that work takes. The library has no jobs of its own;
466
+ this sketch keeps them in memory, on one server:
467
+
468
+ ```ts
469
+ // ingestFailure is the helper above.
470
+ import { randomUUID } from "node:crypto";
471
+ import { toDocumentSummary, type DocumentSummary, type IngestInput } from "llm-large-files";
472
+ import { ingestFailure } from "./ingest-failure.js";
473
+ import { files } from "./large-files.js";
474
+
475
+ export type UploadJob = { state: "working" } | { state: "ready"; document: DocumentSummary } | { state: "failed"; error: string };
476
+
477
+ // One server. With several, keep the jobs where all of them can read them: your database.
478
+ const jobs = new Map<string, { owner: string | undefined; job: UploadJob }>();
479
+
480
+ /** Starts an ingest, and returns its job ID at once: answer 202 with it. */
481
+ export function startIngest(input: IngestInput): string {
482
+ const id = randomUUID();
483
+ const set = (job: UploadJob) => jobs.set(id, { owner: input.owner, job });
484
+ set({ state: "working" });
485
+ files.ingest(input).then(
486
+ (meta) => set({ state: "ready", document: toDocumentSummary(meta) }),
487
+ (error: unknown) => set({ state: "failed", error: ingestFailure(error).error }),
488
+ ).finally(() => setTimeout(() => jobs.delete(id), 60 * 60 * 1000).unref());
489
+ return id;
490
+ }
491
+
492
+ /** GET /api/uploads/:id: the job, when it is this owner's. The browser asks until it is not "working". */
493
+ export function uploadJob(id: string, owner: string | undefined): UploadJob | undefined {
494
+ const entry = jobs.get(id);
495
+ return entry && entry.owner === owner ? entry.job : undefined;
496
+ }
497
+ ```
498
+
499
+ The bytes stay in memory until `ingest` is done with them, so count the uploads in flight when you
500
+ size your servers ([Deployment](./deployment.md)).
501
+
502
+ ## Upload from the browser
503
+
504
+ ```ts
505
+ import type { DocumentSummary } from "llm-large-files";
506
+
507
+ /** Sends one file to POST /api/documents. Throws with a message you can show. */
508
+ export async function uploadFile(file: File): Promise<DocumentSummary> {
509
+ const response = await fetch("/api/documents", {
510
+ method: "POST",
511
+ headers: {
512
+ "Content-Type": "application/octet-stream",
513
+ "X-File-Name": encodeURIComponent(file.name),
514
+ ...(file.type ? { "X-File-Type": file.type } : {}),
515
+ },
516
+ body: file,
517
+ });
518
+ // An error page of a proxy (a 413 or a 502) is not JSON: the status then makes the message.
519
+ const result = (await response.json().catch(() => ({}))) as Partial<DocumentSummary> & { error?: string };
520
+ if (!response.ok || !result.id) throw new Error(result.error ?? `The upload failed (HTTP ${response.status}).`);
521
+ return result as DocumentSummary; // keep result.id with the chat session
522
+ }
523
+ ```
524
+
525
+ - The `import type` is erased when the page is built, so the browser loads nothing of the library.
526
+ - `encodeURIComponent` is needed: `fetch` refuses a header value with characters outside Latin-1,
527
+ and a file name can have any.
528
+ - `fetch` reports no progress of an upload. For a progress bar on large files, send the same
529
+ request with `XMLHttpRequest` and listen to `upload.onprogress`.
530
+ - Every file can take this path. A file small enough to fit in the request is sent to the model
531
+ whole anyway; only the larger ones are searched ([How it works](../how-it-works.md)).
532
+ - Show `estimatedTokens`, `lines` or `pages` next to the file if you like: they come with the
533
+ summary. So do `encoding` and `replacedCharacters`, for a text file that was not valid UTF-8:
534
+ "read as windows-1255", or "12 characters could not be read: save the file as UTF-8 and attach
535
+ it again".
536
+
537
+ ### Upload with progress
538
+
539
+ New in 0.7.0. A large PDF or DOCX can take a while to read once it has arrived. Send the same
540
+ request with `Accept: text/event-stream`, and `upload` answers with the ingest's events as
541
+ Server-Sent Events: how far each stage is, then the summary. The checks that run before the ingest
542
+ (the name, `getOwner`, a body already parsed, the size) still answer with their status and JSON, so
543
+ read the response as JSON when it is not `200`:
544
+
545
+ ```ts
546
+ // upload-progress.ts: runs in the browser. readEvents is the function in "Reading the events in the browser".
547
+ import type { DocumentSummary, IngestEvent, IngestStage } from "llm-large-files";
548
+ import { readEvents } from "./chat-client.js";
549
+
550
+ const STAGES: Record<IngestStage, string> = {
551
+ decode: "Decoding",
552
+ extract: "Reading",
553
+ check: "Checking the pages",
554
+ pictures: "Finding pictures",
555
+ prepare: "Preparing the text",
556
+ index: "Indexing",
557
+ store: "Saving",
558
+ };
559
+
560
+ /** Sends one file to POST /api/documents and reports how far the server has read it. Throws with a message you can show. */
561
+ export async function uploadWithProgress(file: File, onProgress: (text: string) => void): Promise<DocumentSummary> {
562
+ const response = await fetch("/api/documents", {
563
+ method: "POST",
564
+ headers: {
565
+ "Content-Type": "application/octet-stream",
566
+ "X-File-Name": encodeURIComponent(file.name),
567
+ ...(file.type ? { "X-File-Type": file.type } : {}),
568
+ Accept: "text/event-stream",
569
+ },
570
+ body: file,
571
+ });
572
+ // A missing name, a refused owner or a file too large is still an HTTP error, in JSON.
573
+ if (!response.ok) {
574
+ const body = (await response.json().catch(() => ({}))) as { error?: string };
575
+ throw new Error(body.error ?? `The upload failed (HTTP ${response.status}).`);
576
+ }
577
+ let document: DocumentSummary | undefined;
578
+ let failure: string | undefined;
579
+ await readEvents(response, (data) => {
580
+ const event = data as IngestEvent;
581
+ if (event.type === "ingest.progress") {
582
+ const of = event.total !== undefined ? ` of ${event.total.toLocaleString()}` : "";
583
+ onProgress(`${STAGES[event.stage]}: ${event.done.toLocaleString()}${of} ${event.unit}…`);
584
+ } else if (event.type === "ingest.finish") {
585
+ document = event.document; // the summary a 201 answer holds: keep document.id with the chat session
586
+ } else if (event.type === "ingest.error") {
587
+ failure = event.error.message; // the message the JSON answer would have
588
+ }
589
+ });
590
+ if (document) return document;
591
+ throw new Error(failure ?? "The upload stopped before the file was read. Attach it again.");
592
+ }
593
+ ```
594
+
595
+ - **The events start once the whole file has arrived.** They report the server's work on it, not
596
+ the upload of its bytes: for that, use `XMLHttpRequest` and `upload.onprogress`, as above.
597
+ - **`ingest.progress`** has a `stage` (`decode`, `extract`, `check`, `pictures`, `prepare`,
598
+ `index`, `store`), `done`, `total` when it is known, and a `unit` (`pages`, `parts`, `bytes`,
599
+ `characters`): see [stages and units](../reference/events.md#stages-and-units). A stage reports
600
+ at most about every 12 ms, and once more when it ends. Not every file goes through every stage,
601
+ and a stage with nothing to report may send nothing.
602
+ - **The stream ends with one `ingest.finish` or one `ingest.error`.** `ingest.finish` holds in
603
+ `document` the summary a `201` holds. `ingest.error` holds in `error` the `message` and `status`
604
+ the JSON answer would have: `422` and "This file looks binary, not text. …", say. A store's own
605
+ message is never in it.
606
+ - **Closing the page stops the ingest**, as it does for a JSON upload: nothing is stored.
607
+ - **A wildcard does not ask for events.** `Accept: */*` or `text/*` keeps the `201` and JSON, and so
608
+ does `q=0`. The rules are in the [node reference](../reference/node.md#upload-with-progress-accept-textevent-stream).
609
+
610
+ ## Streaming the answer
611
+
612
+ A question can take minutes: searches, reads, a whole-file read of many parts, then the answer.
613
+ There are two ways to show it in the page as it goes:
614
+
615
+ - **The event stream.** New in 0.7.0. Everything the question does comes as a typed event, in
616
+ order: the plan, each model request, each tool call with its progress and outcome, the text, and
617
+ the result. `writeSseEvents` sends the events to the browser as Server-Sent Events, one message
618
+ per event. Use it for a new page.
619
+ - **The three callbacks** `onText`, `onActivity` and `onStep`. They get the same strings at the
620
+ same moments as in 0.6.0, and a route of your own writes them to the browser. Code that uses
621
+ them needs no change: see [the three callbacks](#the-three-callbacks-the-older-way).
622
+
623
+ ### The event stream
624
+
625
+ `askStream(options)` takes the [`AskOptions`](../reference/ask.md#askoptions) of `askWithFiles` and
626
+ returns the question's events as an async iterable:
627
+
628
+ ```ts
629
+ import { askStream } from "llm-large-files";
630
+
631
+ const stream = askStream({ files, model, documentIds, messages, owner });
632
+ for await (const event of stream) {
633
+ if (event.type === "text") process.stdout.write(event.delta);
634
+ if (event.type === "run.error") console.log(event.error.message);
635
+ }
636
+ const result = await stream.result; // what askWithFiles returns, toolTurns included
637
+ ```
638
+
639
+ | Member | What it is |
640
+ |---|---|
641
+ | The iterable | The events, in order. It ends after the last one. |
642
+ | `result` | A promise of what `askWithFiles` returns, `toolTurns` included. It rejects with the question's error. Awaiting it is optional: it never goes unhandled. |
643
+ | `abort(reason?)` | Stops the question. The events end after its `run.error`. |
644
+
645
+ `askGemini` builds its models from the endpoint, explorer included. To stream it, wrap it in
646
+ `eventStream`, which does the same for any function that takes an `onEvent` and a `signal`:
647
+
648
+ ```ts
649
+ import { eventStream, type AskEvent, type AskResult } from "llm-large-files";
650
+ import { askGemini } from "llm-large-files/gemini";
651
+
652
+ const stream = eventStream<AskEvent, AskResult>(
653
+ (onEvent, signal) => askGemini({ files, endpoint, documentIds, messages, owner, streamText: true, onEvent, signal }),
654
+ { signal: deadline }, // optional: a signal of yours that stops the question too
655
+ );
656
+ ```
657
+
658
+ What to know about the stream:
659
+
660
+ - **One run, in order.** Every event has its `type`, a `seq` (1, 2, 3… with no gaps), the `runId`
661
+ ("run_" and 16 hex digits, or the `runId` you pass) and its `time` (milliseconds since 1970).
662
+ `run.start` comes first. Exactly one event comes last: `run.finish` when the question returns,
663
+ `run.error` when it throws, an abort included. Nothing comes after it.
664
+ - **The question runs at once.** Its events wait in memory until you read them. Read them once: a
665
+ second loop over the same stream throws a `TypeError`.
666
+ - **Leaving the loop stops the question.** A `break`, a `return` or a throw in the loop aborts it.
667
+ - **The loop never throws.** A question that fails ends the loop after its `run.error` event. Read
668
+ the error there, or await `result`, which rejects with it.
669
+ - **Errors in events are safe to show.** An event's error is an `EventError`: `message`, and `kind`,
670
+ `status` and `name` when there are any. A model error is told by its kind and status ("The model
671
+ was busy (HTTP 429)."), never in the provider's words, which can name projects, hosts or keys. A
672
+ storage error is told by its code. The provider's words stay on the error that `result` rejects
673
+ with, for your log.
674
+ - **Events hold no text of your documents.** They hold labels, steps, the arguments the model sent,
675
+ and the lines and pages each call showed (`evidence`), but not what the tools returned: `tool.end`
676
+ has no `result`, and the result in `run.finish` and `run.error` has no `toolTurns`.
677
+ `eventResults: true` puts both in. Leave it off for a stream to a browser.
678
+ - **The answer streams.** `askStream` asks the model for the answer as it is written: `streamText`
679
+ is true unless you set it to false. `askGemini` and `askWithFiles` with `onEvent` alone do not:
680
+ `streamText` defaults to true only when `onText` is set, so the text of each reply then comes in
681
+ one `text` event once the reply is in. Pass `streamText: true`, as above. More in
682
+ [when the text streams](#when-the-text-streams).
683
+ - **The callbacks still work.** Pass `onText`, `onActivity` and `onStep` too, and they get what they
684
+ always did. Each `notice` event says where its message went in the callbacks (`display`).
685
+ - **Evidence names its call.** Each entry of `result.evidence` has a `callId` ("call_3"): the call
686
+ whose `tool.end` carries the same entry. A list of sources can point back to the list of tools.
687
+ - **A listener that throws ends the question** with that error, as a callback that throws always
688
+ did. `askStream` gives each event to the stream before your own `onEvent`, so the stream still
689
+ gets the last one. Changed in 0.7.0: a throw from `onActivity` or `onEvent` while a whole-file
690
+ read runs now ends the question too; 0.6.0 made it that tool call's error and went on.
691
+
692
+ Every event and its fields are in the [events reference](../reference/events.md#askevent), with
693
+ the order they come in and how the callbacks map to them.
694
+
695
+ ### A Server-Sent Events route
696
+
697
+ The route below streams one question of a chat with `writeSseEvents` from `llm-large-files/node`.
698
+ It writes the event-stream headers, sends each event as one message, writes a keep-alive comment
699
+ every 15 seconds, and stops the question when the browser goes away:
700
+
701
+ ```ts
702
+ // chat-route.ts
703
+ import type { Request, Response } from "express";
704
+ import { eventStream, partialResultOf, type AskEvent, type AskResult, type ChatTurn, type ToolTurn, type UsageTotals } from "llm-large-files";
705
+ import { askGemini } from "llm-large-files/gemini";
706
+ import { sseMessageOf, writeSseEvents } from "llm-large-files/node";
707
+ import { endpoint, files } from "./large-files.js";
708
+
709
+ /** Your app's chats (in MongoDB, say). Conversations has what to keep and how to build the history. */
710
+ export type ChatStore = {
711
+ /** The chat's documents and its history so far, when the chat is this user's. */
712
+ load(sessionId: string, userId: string): Promise<{ documentIds: string[]; history: Array<ChatTurn | ToolTurn> } | undefined>;
713
+ /** Keeps a question with its tool rounds, its answer when there is one, and what it used. */
714
+ save(sessionId: string, turn: { question: string; toolTurns: ToolTurn[]; answer?: string; usage: UsageTotals }): Promise<void>;
715
+ };
716
+
717
+ const TOO_LONG = "The question took too long. Ask again, or ask about less.";
718
+
719
+ /** POST /api/chat with { sessionId, question }. */
720
+ export function chatRoute(chats: ChatStore) {
721
+ return async (req: Request, res: Response): Promise<void> => {
722
+ // Everything that can be refused is refused before the stream starts, with a status.
723
+ const userId = currentUserId(req);
724
+ if (!userId) return void res.status(401).json({ error: "Sign in to ask." });
725
+ const { sessionId, question } = (req.body ?? {}) as { sessionId?: unknown; question?: unknown };
726
+ if (typeof sessionId !== "string" || typeof question !== "string" || !question.trim()) {
727
+ return void res.status(400).json({ error: "Send a sessionId and a question." });
728
+ }
729
+ const chat = await chats.load(sessionId, userId);
730
+ if (!chat) return void res.status(404).json({ error: "No such chat." });
731
+
732
+ // The question runs at once; its events wait until writeSseEvents reads them.
733
+ const deadline = AbortSignal.timeout(15 * 60 * 1000);
734
+ const stream = eventStream<AskEvent, AskResult>(
735
+ (onEvent, signal) => askGemini({
736
+ files,
737
+ endpoint,
738
+ owner: userId, // the owner the documents were uploaded with
739
+ documentIds: chat.documentIds, // every document of the chat, on every question
740
+ messages: [...chat.history, { role: "user", text: question }],
741
+ streamText: true, // the answer as it is written: without onText, askGemini asks for it only when told
742
+ onEvent,
743
+ signal, // aborts at the deadline, when the browser goes away, or on stream.abort()
744
+ }),
745
+ { signal: deadline },
746
+ );
747
+
748
+ // From here on the answer is a stream: its status is 200, whatever happens next.
749
+ await writeSseEvents(res, stream, {
750
+ end: false, // the response stays open until the question is kept, below
751
+ // Every event as it is, but the deadline in words of your own.
752
+ map: (event) => sseMessageOf(
753
+ event.type === "run.error" && deadline.aborted ? { ...event, error: { ...event.error, message: TOO_LONG } } : event,
754
+ ),
755
+ });
756
+
757
+ // The result with its toolTurns comes from here, never from the events.
758
+ let result: AskResult | undefined;
759
+ try {
760
+ result = await stream.result;
761
+ } catch (error) {
762
+ // The provider's own words are on this error: for your log, not for the page.
763
+ if (!(error instanceof DOMException && error.name === "AbortError")) console.error("A question failed", error);
764
+ // What a failed or stopped question read and paid for, so that asking again need not search again.
765
+ result = partialResultOf(error);
766
+ }
767
+ if (result) {
768
+ await chats.save(sessionId, {
769
+ question,
770
+ toolTurns: result.toolTurns,
771
+ ...(result.answered ? { answer: result.text } : {}),
772
+ usage: result.usage,
773
+ }).catch((error: unknown) => console.error("could not keep the question", error));
774
+ }
775
+ if (!res.writableEnded && !res.destroyed) res.end();
776
+ };
777
+ }
778
+ ```
779
+
780
+ Mount it after `express.json()`, next to the upload routes:
781
+
782
+ ```ts
783
+ // server.ts, after the upload routes. chats is your ChatStore.
784
+ app.post("/api/chat", chatRoute(chats));
785
+ app.listen(3000);
786
+ ```
787
+
788
+ What the route does, and why:
789
+
790
+ - **It refuses before it streams.** A missing user, a bad body or an unknown chat gets a status and
791
+ a JSON error. Once `writeSseEvents` has sent the `200`, an error can only be a `run.error` event.
792
+ - **`writeSseEvents` does the stream's work.** It writes `200` with
793
+ `Content-Type: text/event-stream; charset=utf-8`, `Cache-Control: no-cache, no-transform`,
794
+ `Connection: keep-alive` and `X-Accel-Buffering: no`, and flushes them at once, so the browser's
795
+ `fetch` resolves and the page can show that the question is under way. It waits when the browser
796
+ reads slower than the events come, and it resolves when the events end or the browser has gone.
797
+ Every option is in the [node reference](../reference/node.md#writesseeventsresponse-events-options).
798
+ - **The events go as they are.** The error in `run.error` is already safe to show. The `map` only
799
+ puts the deadline in words of its own: without it, the page would read the deadline's own message
800
+ ("The operation was aborted due to timeout"). For your own words for every error, map on
801
+ `event.error.kind` (a [`ModelErrorKind`](../reference/errors-and-retries.md#modelerrorkind)) and
802
+ `event.error.name` ("DocumentsNotFoundError", "DocumentStoreError"), as the
803
+ [example server](#the-example-server-examplesserverts) does.
804
+ - **The question is kept before the stream ends.** `end: false` keeps the response open after
805
+ `run.finish` while `chats.save` runs, and the route ends it after. A page that lets the user ask
806
+ again only once the stream has closed, as the one [below](#reading-the-events-in-the-browser)
807
+ does, never sends a follow-up before the last question is in the history.
808
+ - **The tool rounds come from `stream.result`**, or from `partialResultOf(error)` when the question
809
+ failed or was stopped: see [where to keep `toolTurns`](#where-to-keep-toolturns).
810
+
811
+ With another model, call `askStream({ files, model, explorer, ... })` in place of `eventStream` and
812
+ `askGemini`: it takes the same `owner`, `documentIds`, `messages` and `signal`, streams the text
813
+ without `streamText`, and its `result` is the same.
814
+
815
+ ### What the browser receives
816
+
817
+ Each message is one event: its `seq` as the `id:`, its `type` as the `event:`, and the event itself
818
+ as JSON in one `data:` line. The `data` carries `type`, `seq`, `runId` and `time` too, so a page
819
+ can read the `data` alone:
820
+
821
+ ```text
822
+ id: 7
823
+ event: tool.start
824
+ data: {"type":"tool.start","callId":"call_1","tool":"search_document","args":{"document_id":"doc_3f9c…","query":"timeout","mode":"exact"},"label":"Search app.log (exact) for “timeout”","documentId":"doc_3f9c…","round":1,"seq":7,"runId":"run_8d2c41f07a9e3b65","time":1795374541651}
825
+ ```
826
+
827
+ Between events, a comment line `: keep-alive` comes every 15 seconds. The events a page uses:
828
+
829
+ | `type` | Fields to read | Show it as |
830
+ |---|---|---|
831
+ | `run.start` | `models` (`answer`, and `explorer` when there is one), `documentIds` | Optional: the question is under way. |
832
+ | `plan` | `inline` and `searchable`: the documents sent whole and those searched, each with `id`, `name`, `format`, `estimatedTokens` and `pages` | Optional: "Searching app.log". It comes again when the question is planned again. |
833
+ | `tool.start` | `callId`, `tool`, `args`, `label`, `documentId`, `round` | A new line in the list of tools, and the status line: `label` and "…". |
834
+ | `tool.progress` | `callId`, `stage` (`"map"` or `"reduce"`), `done`, `total`, `message` | A whole-file read: a counter on that call's line, and the status line: `message` and "…". |
835
+ | `tool.end` | `callId`, `outcome` (`"ok"`, `"error"`, `"refused"`, `"already_shown"`, `"not_run"`), `ms`, `step`, `evidence`, `error` | The call's line, done: `step`, with a mark for the outcome. `step` is what `onStep` gets; it is absent for `"not_run"` and for a call ended because its turn failed. |
836
+ | `text` | `delta`, `requestId` | The answer, growing. The deltas add up to the result's `text`. |
837
+ | `notice` | `code`, `message`, `display` | `display` `"activity"`: the status line. `"step"`: a line in the list. `"none"`: notices earlier versions did not show, such as `budget_reached` and `blocked`; show them if you like. |
838
+ | `retry` | `requestId`, `attempt`, `delayMs`, `error`, `message` | The status line: `message` ("The model did not answer (HTTP 503). Trying again in 2 s…"). |
839
+ | `request.start`, `request.end` | `requestId`, `role`, `purpose`, `model`, `turn`; `ms`, `outcome`, `usage`, `error` | Usually not shown. For your logs and timings. |
840
+ | `run.finish` | `result` (below) | The summary under the answer. Last. |
841
+ | `run.error` | `error`, `partial` (below) | The error, and the answer so far marked as cut off. Last. |
842
+
843
+ `writeSseEvents` sends every event as it is, except the last one, which it sends smaller
844
+ ([`sseMessageOf`](../reference/node.md#ssemessageofevent)):
845
+
846
+ | Event | `data` besides `type`, `seq`, `runId` and `time` |
847
+ |---|---|
848
+ | `run.finish` | `result`: `answered`, `text`, `finishReason` and `blockReason` (when there are any), `steps`, `evidence`, `turns` and `usage`. Not `toolTurns`, `plan`, `budget` or `lastUsage`. |
849
+ | `run.error` | `error`: `message`, and `kind`, `status` and `name` when there are any. `partial`: `steps`, `evidence` and `usage` of what the question found before it failed. `partial` is left out when there is none. |
850
+
851
+ Labels, steps and messages are English sentences made by the library, one line of plain text each,
852
+ with file names and the model's search words in them. Render them as plain text, never as markdown
853
+ or HTML ([the three callbacks](#the-three-callbacks-the-older-way) says how they are cleaned).
854
+
855
+ ### Where to keep `toolTurns`
856
+
857
+ On the server. The tool rounds of a question hold the text the tools returned, and the next
858
+ question of the chat needs them in its history ([Conversations](./conversations.md)). The events
859
+ do not carry them, so take them from what the question returns:
860
+
861
+ - `await stream.result`, when the question returned;
862
+ - `partialResultOf(error)`, when `stream.result` rejected: what a failed or stopped question read
863
+ and paid for, so that asking again need not search again.
864
+
865
+ `eventResults: true` would put them in `run.finish`, but `writeSseEvents` leaves them out of what it
866
+ sends anyway, and it would put each tool result in its `tool.end`, which it does send. Keep
867
+ `eventResults` off in a route to a browser.
868
+
869
+ ### When the browser goes away
870
+
871
+ The user presses Stop, closes the tab or loses the connection, and the response closes.
872
+ `writeSseEvents` sees it at once, even while it waits for the next event: it stops reading, calls
873
+ the stream's `return()`, and resolves. For an `askStream` or an `eventStream` passed in directly,
874
+ that aborts the question: the request under way stops, and no other tool call starts.
875
+ `stream.result` then rejects with an `AbortError` ("The events stopped being read."), and
876
+ `partialResultOf` of it gives what the question found, which the route above keeps. Nothing more is
877
+ written: the `run.error` of the stopped question is not sent.
878
+
879
+ That holds only for the stream itself. An async generator that wraps it, to rename or skip events,
880
+ is stopped only when it next yields, and a question waiting on a long model request goes on, and
881
+ costs, until then. To change what is sent, use `map`, and return `undefined` from it to skip an
882
+ event. If you do wrap the stream, stop the question yourself:
883
+ `res.once("close", () => stream.abort())`. The
884
+ [node reference](../reference/node.md#when-the-client-goes-away) has both.
885
+
886
+ ### Reading the events in the browser
887
+
888
+ `EventSource` sends only `GET` requests without a body, so read a `POST` stream with `fetch`. This
889
+ reader splits the stream into messages, joins the `data:` lines of each, and parses them as JSON:
890
+
891
+ ```ts
892
+ // chat-client.ts: runs in the browser.
893
+ import type { AskEvent, EventResult } from "llm-large-files";
894
+
895
+ /** The result in run.finish, as sseMessageOf sends it. */
896
+ export type FinishResult = Pick<EventResult, "answered" | "text" | "finishReason" | "blockReason" | "steps" | "evidence" | "turns" | "usage">;
897
+ /** What run.error keeps of what the question found. */
898
+ export type PartialResult = Pick<EventResult, "steps" | "evidence" | "usage">;
899
+ /** The data of each message: the event itself, with run.finish and run.error made smaller. */
900
+ export type ChatEvent =
901
+ | Exclude<AskEvent, { type: "run.finish" | "run.error" }>
902
+ | (Omit<Extract<AskEvent, { type: "run.finish" }>, "result"> & { result: FinishResult })
903
+ | (Omit<Extract<AskEvent, { type: "run.error" }>, "partial"> & { partial?: PartialResult });
904
+
905
+ /**
906
+ * Calls `on` with the data of each message of an event stream, until the stream ends. Comments
907
+ * (keep-alive) are skipped, and so is a message that is not JSON.
908
+ */
909
+ export async function readEvents(response: Response, on: (data: unknown) => void): Promise<void> {
910
+ const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();
911
+ let buffer = "";
912
+ for (;;) {
913
+ const { value, done } = await reader.read();
914
+ if (done) return;
915
+ buffer += value;
916
+ // A message ends at a blank line. Lines end in "\n" ("\r\n" through some proxies), never in
917
+ // U+2028 or U+2029: split on those two endings only.
918
+ let end: RegExpExecArray | null;
919
+ while ((end = /\r?\n\r?\n/.exec(buffer))) {
920
+ const block = buffer.slice(0, end.index);
921
+ buffer = buffer.slice(end.index + end[0].length);
922
+ const data = block.split(/\r?\n/)
923
+ .filter((line) => line.startsWith("data:"))
924
+ .map((line) => line.slice(line.startsWith("data: ") ? 6 : 5))
925
+ .join("\n");
926
+ if (!data) continue; // a comment: ": keep-alive"
927
+ let parsed: unknown;
928
+ try {
929
+ parsed = JSON.parse(data);
930
+ } catch (error) {
931
+ console.error("An event could not be read", error); // one bad message does not stop the others
932
+ continue;
933
+ }
934
+ on(parsed);
935
+ }
936
+ }
937
+ }
938
+ ```
939
+
940
+ A page that uses it builds four things from the events: a status line that the next activity
941
+ replaces, a list of tool calls with their outcome and the progress of whole-file reads, the answer
942
+ as it streams, and a summary when the question ends. It has a Stop button too:
943
+
944
+ ```ts
945
+ // chat-page.ts: runs in the browser. readEvents and ChatEvent are above.
946
+ import type { Evidence, ToolOutcome } from "llm-large-files";
947
+ import { readEvents, type ChatEvent, type FinishResult } from "./chat-client.js";
948
+
949
+ const statusView = document.querySelector<HTMLElement>("#status")!;
950
+ const toolsView = document.querySelector<HTMLUListElement>("#tools")!;
951
+ const answerView = document.querySelector<HTMLElement>("#answer")!;
952
+ const summaryView = document.querySelector<HTMLElement>("#summary")!;
953
+ const askButton = document.querySelector<HTMLButtonElement>("#ask")!;
954
+ const stopButton = document.querySelector<HTMLButtonElement>("#stop")!;
955
+
956
+ const MARKS: Record<ToolOutcome, string> = { ok: "✓", error: "✗", refused: "–", already_shown: "↺", not_run: "–" };
957
+
958
+ /** "app.log lines 120-180, 300", or the pages of a PDF. */
959
+ const sourceOf = (evidence: Evidence) => {
960
+ const ranges = evidence.lines ?? evidence.pages;
961
+ const where = ranges?.map(([from, to]) => (from === to ? `${from}` : `${from}-${to}`)).join(", ");
962
+ return `${evidence.document ?? evidence.documentId}${where ? ` ${evidence.lines ? "lines" : "pages"} ${where}` : ""}`;
963
+ };
964
+
965
+ /** One line under the answer: what was read, and what it took. */
966
+ function summaryOf(result: FinishResult): string {
967
+ if (!result.answered) {
968
+ return result.blockReason ? "This question was blocked by the model's safety filters." : "No answer this time. Ask again, or ask more precisely.";
969
+ }
970
+ const sources = [...new Set(result.evidence.map(sourceOf))];
971
+ return `${sources.length ? `Sources: ${sources.join("; ")}. ` : ""}${result.usage.requests} model requests.`;
972
+ }
973
+
974
+ export async function showAnswer(sessionId: string, question: string): Promise<void> {
975
+ const controller = new AbortController();
976
+ stopButton.onclick = () => controller.abort(); // the server sees the connection close, and stops the question
977
+ askButton.disabled = true;
978
+ statusView.textContent = "Asking…";
979
+ toolsView.replaceChildren();
980
+ answerView.textContent = "";
981
+ summaryView.textContent = "";
982
+ const calls = new Map<string, { label: string; item: HTMLLIElement }>();
983
+ const listItem = (text: string, className?: string) => {
984
+ const item = document.createElement("li");
985
+ item.textContent = text; // text, never HTML: labels hold file names and the model's search words
986
+ if (className) item.className = className;
987
+ toolsView.append(item);
988
+ return item;
989
+ };
990
+ let answer = "";
991
+ let ended = false;
992
+ try {
993
+ const response = await fetch("/api/chat", {
994
+ method: "POST",
995
+ headers: { "Content-Type": "application/json" },
996
+ body: JSON.stringify({ sessionId, question }),
997
+ signal: controller.signal,
998
+ });
999
+ if (!response.ok || !response.body) {
1000
+ const body = (await response.json().catch(() => ({}))) as { error?: string };
1001
+ statusView.textContent = body.error ?? `The server answered HTTP ${response.status}.`;
1002
+ return;
1003
+ }
1004
+ await readEvents(response, (data) => {
1005
+ const event = data as ChatEvent;
1006
+ switch (event.type) {
1007
+ case "tool.start":
1008
+ calls.set(event.callId, { label: event.label, item: listItem(`… ${event.label}`) });
1009
+ statusView.textContent = `${event.label}…`;
1010
+ break;
1011
+ case "tool.progress": {
1012
+ // A whole-file read: how many of its parts are read, or of its notes combined.
1013
+ const call = calls.get(event.callId);
1014
+ if (call) call.item.textContent = `… ${call.label} (${event.done}/${event.total})`;
1015
+ statusView.textContent = `${event.message}…`;
1016
+ break;
1017
+ }
1018
+ case "tool.end": {
1019
+ const call = calls.get(event.callId);
1020
+ if (call) {
1021
+ call.item.textContent = `${MARKS[event.outcome]} ${event.step ?? call.label}`;
1022
+ call.item.className = event.outcome;
1023
+ }
1024
+ break;
1025
+ }
1026
+ case "notice":
1027
+ if (event.display === "activity") statusView.textContent = event.message;
1028
+ if (event.display === "step") listItem(`· ${event.message}`);
1029
+ break;
1030
+ case "retry":
1031
+ statusView.textContent = event.message;
1032
+ break;
1033
+ case "text":
1034
+ answer += event.delta;
1035
+ answerView.textContent = answer;
1036
+ statusView.textContent = "";
1037
+ break;
1038
+ case "run.finish":
1039
+ ended = true;
1040
+ statusView.textContent = "";
1041
+ summaryView.textContent = summaryOf(event.result);
1042
+ if (!event.result.answered) answerView.textContent = "";
1043
+ break;
1044
+ case "run.error":
1045
+ ended = true;
1046
+ statusView.textContent = event.error.message; // safe to show: never the provider's own words
1047
+ if (answer) answerView.textContent = `${answer}\n\n(The answer was cut off.)`;
1048
+ break;
1049
+ }
1050
+ });
1051
+ if (!ended) statusView.textContent = "The connection closed before the answer was complete. Ask again.";
1052
+ } catch {
1053
+ statusView.textContent = controller.signal.aborted ? "Stopped." : "The connection was lost. Ask again.";
1054
+ if (answer) answerView.textContent = `${answer}\n\n(The answer was cut off.)`;
1055
+ } finally {
1056
+ // Only once the stream has closed: by then the server has kept the question.
1057
+ askButton.disabled = false;
1058
+ }
1059
+ }
1060
+ ```
1061
+
1062
+ - **The page reads `data` alone.** Every message's data is the event, with its `type`, so the
1063
+ `event:` line is not needed. `import type` is erased when the page is built: the browser loads
1064
+ nothing of the library.
1065
+ - **Line breaks.** The reader splits on `"\n"` and `"\r\n"` only. JSON may hold U+2028 and U+2029,
1066
+ which some readers take for line breaks; `writeSseEvents` writes them as `\u2028` and `\u2029`,
1067
+ so even such a reader gets each message whole.
1068
+ - **`JSON.parse` is in a `try`.** A message the page cannot read, from a proxy or a server of
1069
+ another version, is logged and skipped, and the stream goes on.
1070
+ - **The text.** Without an explorer model, the text can hold a remark the model wrote before it
1071
+ called a tool ("I'll search the log for the failed job."); the next reply's text then starts
1072
+ after `"\n\n"`. With an [explorer model](./explorer-model.md), it is only the answer.
1073
+ - **`answered: false`** means the text is no answer: a blocked prompt, a reply cut off before its
1074
+ first word, or an answer that had no text even when it was asked for once more. Show your own
1075
+ message in its place, as above, and do not store it as the assistant's turn (the route does not).
1076
+ - **`run.error` after some text** leaves the text that arrived. Keep it, mark it as cut off, and let
1077
+ the user ask again.
1078
+ - **Ask is enabled again only when the stream has closed**, not at `run.finish`: the route keeps the
1079
+ question before it ends the response.
1080
+ - **Stop** aborts the `fetch`. The connection closes, the server stops the question, and the
1081
+ reader rejects with an `AbortError`.
1082
+ - **A connection that drops** ends the stream without `run.finish` or `run.error`, or makes a read
1083
+ fail. Either way the page says so: the question cannot be resumed.
1084
+
1085
+ ### When the text streams
1086
+
1087
+ Whether the model is asked for the answer as it is written is `streamText`. It defaults to true when
1088
+ `onText` is set and in `askStream`, and to false otherwise: an `onEvent` alone does not change how
1089
+ the model is asked. When the text does not stream, each reply reaches `onText` and the `text`
1090
+ events once it is in: in one piece with `streamText` off, and with it on but an endpoint that
1091
+ cannot stream, in one piece too, or from Gemini, one piece for each text part. When it does,
1092
+ a reply that fails after its first piece of text is not sent again: the question throws, and
1093
+ `partialResultOf(error).text` holds what was shown.
1094
+
1095
+ With `streamText` on, whether the provider streams:
1096
+
1097
+ - **`askGemini` and `gemini()`**: when the endpoint has a `streamUrl`. `vertexAi()` and
1098
+ `geminiApi()` set one; an endpoint of your own for a gateway needs it
1099
+ ([Gemini and Vertex AI](./vertex-and-gemini.md)).
1100
+ - **`openAiCompatible()`**: unless `stream: false`
1101
+ ([OpenAI-compatible endpoints](./openai-compatible.md)).
1102
+ - **`anthropic()`**: every chat request, unless `stream: false`, with `streamText` on or off; with
1103
+ it off, the text is passed on once the reply is in ([Claude](./anthropic.md)).
1104
+
1105
+ An OpenAI-compatible server or a Claude gateway that answers without a stream is read in one piece.
1106
+ An explorer model's requests are never shown: `gemini()` and `openAiCompatible()` do not stream
1107
+ them, and `anthropic()` streams them (unless `stream: false`) without showing any of it. So between
1108
+ the question and the first word, a page can get nothing but tool and request events for minutes:
1109
+ an explorer at work, a model that thinks before it writes (up to `firstByteTimeoutMs`, 600 s by
1110
+ default, for each request). Plan the stream for that silence
1111
+ ([below](#keep-alive-comments-and-proxies)).
1112
+
1113
+ ### Keep-alive comments and proxies
1114
+
1115
+ A load balancer or a proxy in front of your server may close a response on which nothing arrived
1116
+ for a while, or hold the events back in a buffer. A question can be silent for minutes (an explorer
1117
+ at work, a model that thinks, a whole-file read between two parts), so:
1118
+
1119
+ - **Write a comment line now and then.** A line that starts with `:` is a comment in Server-Sent
1120
+ Events: it keeps the connection busy, and the browser drops it. `writeSseEvents` writes
1121
+ `: keep-alive` every 15 seconds; `heartbeatMs` changes that, and 0 turns it off.
1122
+ - **Turn off buffering for the route.** `writeSseEvents` sends `X-Accel-Buffering: no`, which asks
1123
+ nginx to pass each event on at once, and `Cache-Control: no-cache, no-transform`: the Express
1124
+ `compression` package skips a response marked `no-transform`, and so does a proxy that honors it.
1125
+ A compression middleware that ignores it still holds events back; leave this route out of it.
1126
+ `headers` adds headers of your own, or replaces these.
1127
+ - **Allow for the whole question in the proxy's timeout.** Keep-alives do not help against a limit
1128
+ on the total time of a response. The route's own deadline (15 minutes above) should end first.
1129
+
1130
+ Proxies, timeouts and several servers are in [Deployment](./deployment.md).
1131
+
1132
+ ### Cancelling
1133
+
1134
+ A question stops when its signal aborts. The route above stops it in two cases:
1135
+
1136
+ - **The browser goes away**: the user pressed Stop, closed the tab, or lost the connection.
1137
+ `writeSseEvents` sees the response close and calls the stream's `return()`, which aborts the
1138
+ question ([above](#when-the-browser-goes-away)). A route of your own without `writeSseEvents`
1139
+ listens on the response, not on the request: the request's own `close` fires once its body has
1140
+ been read, long before the answer is done.
1141
+ - **Your deadline passes**: `AbortSignal.timeout`, passed as the `signal` option of `eventStream`
1142
+ (or of `askStream`). A question has no time limit of its own.
1143
+
1144
+ The question stops at once, even with an adapter of your own that does not look at the signal:
1145
+ nothing more is sent, and text that such an adapter sends later is not shown. `usage` in
1146
+ `partialResultOf(error)` is what was counted when it stopped; a request still running then may be
1147
+ billed by the provider, and is not counted.
1148
+
1149
+ What aborting stops, what a stopped question throws, how to tell your deadline from a user who
1150
+ left, and why to abort with an `Error` rather than a string are in
1151
+ [Errors and reliability](./errors-and-reliability.md#an-overall-deadline).
1152
+
1153
+ There is no resuming: a question whose stream was cut off is over, and the user asks again. With the
1154
+ tool rounds of the stopped question kept, as the route does, the new question starts from what it
1155
+ had found.
1156
+
1157
+ ### The three callbacks: the older way
1158
+
1159
+ The callbacks of earlier versions still work, unchanged: the same strings, at the same moments. A
1160
+ route that sends them to the browser names its own events and writes its own keep-alive. For a new
1161
+ page, use [the event stream](#the-event-stream), which says the same and more, as data.
1162
+
1163
+ `askGemini` and `askWithFiles` take three callbacks for a UI:
1164
+
1165
+ | Callback | Receives | Show it as |
1166
+ |---|---|---|
1167
+ | `onText(delta)` | Pieces of the text the user is meant to read, as they arrive. | The answer, growing. |
1168
+ | `onActivity(text)` | What the question is doing now. | A status line that the next one replaces. |
1169
+ | `onStep(text)` | A step that is done. | A list that grows. The same lines are in `result.steps`. |
1170
+
1171
+ **`onText`.** The pieces add up to `result.text`. They hold:
1172
+
1173
+ - the answer;
1174
+ - without an explorer model, also any remark the model writes before it calls a tool ("I'll search
1175
+ the log for the failed job."). The text of the next reply then starts after `"\n\n"`. An
1176
+ `activity` or `step` after some text means that text was such a remark;
1177
+ - with an [explorer model](./explorer-model.md), only the text of the model that answers: nothing
1178
+ the explorer writes is shown.
1179
+
1180
+ Thoughts are never passed on. Once text of a reply was shown, that reply is not sent again if it
1181
+ fails: the question throws, and `partialResultOf(error).text` holds what was shown.
1182
+
1183
+ **`onActivity`.** One line, ending in "…":
1184
+
1185
+ | When | For example |
1186
+ |---|---|
1187
+ | A document must be searched | "Too large to read at once: app.log. Searching instead…" |
1188
+ | A tool call starts | "Search app.log (keywords) for “timeout”…", "Read app.log lines 120-180…", "Overview of app.log…", "Look at report.pdf pages 2-3…" |
1189
+ | A whole-file read goes on | "Reading app.log: part 3 of 12…", "Combining notes on app.log (round 1): 2 of 4…" |
1190
+ | A request is sent again | "The model did not answer (HTTP 503). Trying again in 2 s…", "The model could not be reached. Trying again…", "The model's reply was cut off on its way. Trying again…", "The model sent nothing for too long. Trying again…" |
1191
+ | The answer is asked for | "Writing the answer…" |
1192
+
1193
+ **`onStep`.** One line for each tool call that ran, with what it found: "Search app.log (exact) for
1194
+ “timeout” — 12 matching lines", "Read app.log lines 120-180", "Look at report.pdf pages 12-14". A
1195
+ call answered from an earlier result ends in " — already shown above", and one that failed in
1196
+ " — failed: " and the reason. A call to a tool that does not exist reads
1197
+ `Call “do_magic” — failed: Unknown tool “do_magic”.`, its name cut at 64 characters. The loop adds
1198
+ its own lines too, such as "Older tool results were shortened to make room in the request" or "The
1199
+ model's answer was empty: it was asked again". Every tool, and `toolResultSummary`, which writes
1200
+ what a step found, are in the [tools reference](../reference/tools.md).
1201
+
1202
+ Activities and steps are English sentences, made by the library, with file names and the model's
1203
+ search words in them. Each is one line of plain text: a line break, a tab or another control
1204
+ character in what the model sent becomes one space, text-direction controls, zero-width spaces
1205
+ and tag characters are dropped (variation selectors and joiners are not), `](` becomes `] (` so
1206
+ that a markdown link or picture in a query stays text, and a query is cut at 80 characters and a
1207
+ task at 100. They still quote the model's words, HTML tags and web addresses included. Render
1208
+ them as plain text, never as markdown or HTML. For a UI in another language, show your own words
1209
+ for each event ("Searching your files…"), and build a list of sources from `result.evidence` when
1210
+ the answer is done: it is the structured record of what each call showed, the document and the
1211
+ lines or pages.
1212
+
1213
+ The same strings are in the events: an activity is a `tool.start` `label`, a `tool.progress`
1214
+ `message` or a `retry` `message` (the first two without the "…"), or a `notice` with `display`
1215
+ `"activity"`; a step is a `tool.end` `step`, or a `notice` with `display` `"step"`.
1216
+
1217
+ **Whole-file reads.** `askGemini` and `askWithFiles` take no `onProgress`. The progress of a
1218
+ whole-file read, a `ProgressEvent` (`kind` "map" or "reduce", `message`, `done`, `total`), reaches
1219
+ `onActivity` as its `message` followed by "…". The event stream tells it apart by call, as
1220
+ `tool.progress` events with the `callId` of the read. `ProgressEvent` and `onProgress` are for a
1221
+ loop of your own: `files.tools(documents, { onProgress })`
1222
+ ([Your own adapter and loop](./own-adapter-and-loop.md)).
1223
+
1224
+ ### A route with the three callbacks
1225
+
1226
+ The route below is the one earlier versions of this guide had. It streams one question of a chat
1227
+ as Server-Sent Events that it writes itself, from the callbacks. Its event names and their data are
1228
+ its own, not those of the event stream: `text` here is a string, where the event stream's `text` is
1229
+ an event with a `delta`. Each event is `event: <name>` and `data: <JSON>`:
1230
+
1231
+ | Event | `data` | When |
1232
+ |---|---|---|
1233
+ | `text` | A string: a piece of the answer. | As it streams, one event for each `onText` call. |
1234
+ | `activity` | A string. | Each `onActivity` call. |
1235
+ | `step` | A string. | Each `onStep` call. |
1236
+ | `done` | `{ answered, blockReason, finishReason, steps, evidence, usage }` | Last, when the question ended without an error. |
1237
+ | `error` | `{ kind, message, incomplete }` | Last, when the question failed. |
1238
+
1239
+ Every 15 seconds the route also writes a comment line, `: keep-alive`, which the browser ignores.
1240
+
1241
+ ```ts
1242
+ // chat-route-callbacks.ts
1243
+ import type { Request, Response } from "express";
1244
+ import {
1245
+ DocumentsNotFoundError,
1246
+ DocumentStoreError,
1247
+ errorKindOf,
1248
+ partialResultOf,
1249
+ type ChatTurn,
1250
+ type ModelErrorKind,
1251
+ type ToolTurn,
1252
+ type UsageTotals,
1253
+ } from "llm-large-files";
1254
+ import { askGemini } from "llm-large-files/gemini";
1255
+ import { endpoint, files } from "./large-files.js";
1256
+
1257
+ /** Your app's chats (in MongoDB, say). Conversations has what to keep and how to build the history. */
1258
+ export type ChatStore = {
1259
+ /** The chat's documents and its history so far, when the chat is this user's. */
1260
+ load(sessionId: string, userId: string): Promise<{ documentIds: string[]; history: Array<ChatTurn | ToolTurn> } | undefined>;
1261
+ /** Keeps a question with its tool rounds, its answer when there is one, and what it used. */
1262
+ save(sessionId: string, turn: { question: string; toolTurns: ToolTurn[]; answer?: string; usage: UsageTotals }): Promise<void>;
1263
+ };
1264
+
1265
+ const MESSAGES: Record<ModelErrorKind, string> = {
1266
+ context_overflow: "This chat is too long for the model. Start a new chat, or ask about fewer files.",
1267
+ quota: "The assistant is not available right now.",
1268
+ rate_limit: "The assistant is busy. Try again in a minute.",
1269
+ timeout: "The model took too long to answer. Try again.",
1270
+ unreachable: "The model could not be reached. Try again.",
1271
+ server: "The model could not answer just now. Try again.",
1272
+ auth: "Something went wrong on our side. Try again later.",
1273
+ invalid: "Something went wrong on our side. Try again later.",
1274
+ };
1275
+
1276
+ /** The error event: a kind the page can act on, and words for the user. The provider's message stays in your log. */
1277
+ function errorEvent(error: unknown, pastDeadline: boolean): { kind: string; message: string } {
1278
+ if (pastDeadline) return { kind: "deadline", message: "The question took too long. Ask again, or ask about less." };
1279
+ if (error instanceof DocumentsNotFoundError) return { kind: "documents_not_found", message: "A file of this chat is no longer available. Attach it again." };
1280
+ if (error instanceof DocumentStoreError) return { kind: "store", message: "Your files could not be read just now. Try again in a moment." };
1281
+ const kind = errorKindOf(error);
1282
+ return kind ? { kind, message: MESSAGES[kind] } : { kind: "other", message: "Something went wrong on our side. Try again later." };
1283
+ }
1284
+
1285
+ /** POST /api/chat with { sessionId, question }. */
1286
+ export function chatRouteWithCallbacks(chats: ChatStore) {
1287
+ return async (req: Request, res: Response): Promise<void> => {
1288
+ // Everything that can be refused is refused before the stream starts, with a status.
1289
+ const userId = currentUserId(req);
1290
+ if (!userId) return void res.status(401).json({ error: "Sign in to ask." });
1291
+ const { sessionId, question } = (req.body ?? {}) as { sessionId?: unknown; question?: unknown };
1292
+ if (typeof sessionId !== "string" || typeof question !== "string" || !question.trim()) {
1293
+ return void res.status(400).json({ error: "Send a sessionId and a question." });
1294
+ }
1295
+ const chat = await chats.load(sessionId, userId);
1296
+ if (!chat) return void res.status(404).json({ error: "No such chat." });
1297
+
1298
+ // From here on the answer is a stream: its status is 200, whatever happens next.
1299
+ res.writeHead(200, {
1300
+ "Content-Type": "text/event-stream; charset=utf-8",
1301
+ "Cache-Control": "no-cache, no-transform",
1302
+ "X-Accel-Buffering": "no", // nginx: pass each event on at once
1303
+ });
1304
+ res.flushHeaders();
1305
+ const write = (chunk: string) => {
1306
+ if (!res.writableEnded && !res.destroyed) res.write(chunk);
1307
+ };
1308
+ const send = (event: string, data: unknown) => write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
1309
+ const keepAlive = setInterval(() => write(": keep-alive\n\n"), 15_000);
1310
+
1311
+ // Stop the question when the browser goes away, or at your deadline.
1312
+ const userLeft = new AbortController();
1313
+ res.on("close", () => userLeft.abort());
1314
+ const deadline = AbortSignal.timeout(15 * 60 * 1000);
1315
+
1316
+ try {
1317
+ const result = await askGemini({
1318
+ files,
1319
+ endpoint,
1320
+ owner: userId, // the owner the documents were uploaded with
1321
+ documentIds: chat.documentIds, // every document of the chat, on every question
1322
+ messages: [...chat.history, { role: "user", text: question }],
1323
+ signal: AbortSignal.any([userLeft.signal, deadline]),
1324
+ onText: (delta) => send("text", delta),
1325
+ onActivity: (text) => send("activity", text),
1326
+ onStep: (text) => send("step", text),
1327
+ });
1328
+ await chats.save(sessionId, {
1329
+ question,
1330
+ toolTurns: result.toolTurns,
1331
+ ...(result.answered ? { answer: result.text } : {}),
1332
+ usage: result.usage,
1333
+ });
1334
+ send("done", {
1335
+ answered: result.answered,
1336
+ blockReason: result.blockReason,
1337
+ finishReason: result.finishReason,
1338
+ steps: result.steps,
1339
+ evidence: result.evidence,
1340
+ usage: result.usage,
1341
+ });
1342
+ } catch (error) {
1343
+ // What a failed question read and paid for: keep it, so that asking again need not search again.
1344
+ const partial = partialResultOf(error);
1345
+ if (partial) {
1346
+ await chats.save(sessionId, { question, toolTurns: partial.toolTurns, usage: partial.usage })
1347
+ .catch((saveError: unknown) => console.error("could not keep a failed question", saveError));
1348
+ }
1349
+ if (userLeft.signal.aborted) return; // nobody is reading
1350
+ console.error("A question failed", error);
1351
+ send("error", { ...errorEvent(error, deadline.aborted), incomplete: Boolean(partial?.text) });
1352
+ } finally {
1353
+ clearInterval(keepAlive);
1354
+ res.end();
1355
+ }
1356
+ };
1357
+ }
1358
+ ```
1359
+
1360
+ It is mounted as the route above is: `app.post("/api/chat", chatRouteWithCallbacks(chats))`.
1361
+
1362
+ What the route does, and why:
1363
+
1364
+ - **It refuses before it streams**, as the route above does. Once `writeHead(200)` is sent, an
1365
+ error can only be an `error` event.
1366
+ - **Every `data` is JSON.** A piece of text can hold a blank line, which would end an event if it
1367
+ were written as it is. `JSON.stringify` keeps each event on one `data:` line.
1368
+ - **`flushHeaders()` sends the 200 at once**, so the browser's `fetch` resolves and the page can
1369
+ show that the question is under way. It writes its own keep-alive every 15 seconds, and stops
1370
+ the question when the response closes ([cancelling](#cancelling)).
1371
+ - **The history comes from your store**, with the tool rounds of earlier questions in their place,
1372
+ and the question is kept with its `toolTurns`, and with its answer only when there is one
1373
+ (`answered`). What to keep, and why, is in [Conversations](./conversations.md). It is kept
1374
+ before `done` is sent, so a follow-up question always finds it.
1375
+ - **`done` carries the result** the page needs: `answered` to know whether the text is an answer,
1376
+ `blockReason` and `finishReason` to say why not, `steps`, `evidence` for sources, and `usage`.
1377
+ Leave out what your users should not see. Counting `usage` per user or session is in
1378
+ [Costs and limits](./costs-and-limits.md).
1379
+ - **`error` carries a kind and words for the user.** `kind` is the error's
1380
+ [`ModelErrorKind`](../reference/errors-and-retries.md#modelerrorkind) for a model error, and a
1381
+ name of the route's own otherwise. The messages follow
1382
+ [Errors and reliability](./errors-and-reliability.md), which says what each error means. The
1383
+ provider's message is in the error the question throws: it goes to the log, never to the page.
1384
+ `incomplete` is true when some of the answer was already shown: the page keeps that text and
1385
+ marks it as cut off.
1386
+
1387
+ With another model, call `askWithFiles({ files, model, ... })` in place of `askGemini`: it takes the
1388
+ same `owner`, `documentIds`, `messages`, `signal` and callbacks, and returns the same result.
1389
+
1390
+ ### Reading that route's stream
1391
+
1392
+ The browser side of the route with the three callbacks reads its `text`, `activity`, `step`,
1393
+ `done` and `error` events with `fetch`:
1394
+
1395
+ ```ts
1396
+ // chat-client-callbacks.ts: runs in the browser.
1397
+ import type { Evidence, UsageTotals } from "llm-large-files";
1398
+
1399
+ /** The data of the `done` event. */
1400
+ export type AnswerEnd = { answered: boolean; blockReason?: string; finishReason?: string; steps: string[]; evidence: Evidence[]; usage: UsageTotals };
1401
+ /** The data of the `error` event. */
1402
+ export type AnswerError = { kind: string; message: string; incomplete: boolean };
1403
+ export type AnswerEvents = { text(delta: string): void; activity(text: string): void; step(text: string): void };
1404
+
1405
+ /**
1406
+ * Asks one question and reads the answer as it streams. Resolves with the `done` event. Rejects on
1407
+ * an `error` event (with its kind and message), an HTTP error, a dropped connection, or an abort.
1408
+ */
1409
+ export async function askStreamed(sessionId: string, question: string, on: AnswerEvents, signal: AbortSignal): Promise<AnswerEnd> {
1410
+ const response = await fetch("/api/chat", {
1411
+ method: "POST",
1412
+ headers: { "Content-Type": "application/json" },
1413
+ body: JSON.stringify({ sessionId, question }),
1414
+ signal,
1415
+ });
1416
+ if (!response.ok || !response.body) {
1417
+ const body = (await response.json().catch(() => ({}))) as { error?: string };
1418
+ throw new Error(body.error ?? `The server answered HTTP ${response.status}.`);
1419
+ }
1420
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
1421
+ let buffer = "";
1422
+ for (;;) {
1423
+ const { value, done } = await reader.read();
1424
+ if (done) break;
1425
+ buffer += value;
1426
+ let end: number;
1427
+ while ((end = buffer.indexOf("\n\n")) >= 0) {
1428
+ const block = buffer.slice(0, end);
1429
+ buffer = buffer.slice(end + 2);
1430
+ let event = "message";
1431
+ let data = "";
1432
+ for (const line of block.split("\n")) {
1433
+ if (line.startsWith("event: ")) event = line.slice(7);
1434
+ else if (line.startsWith("data: ")) data += line.slice(6);
1435
+ // A line that starts with ":" is a keep-alive comment.
1436
+ }
1437
+ if (!data) continue;
1438
+ let payload: unknown;
1439
+ try {
1440
+ payload = JSON.parse(data);
1441
+ } catch {
1442
+ continue; // a message that is not JSON is skipped
1443
+ }
1444
+ if (event === "text") on.text(payload as string);
1445
+ else if (event === "activity") on.activity(payload as string);
1446
+ else if (event === "step") on.step(payload as string);
1447
+ else if (event === "done") return payload as AnswerEnd;
1448
+ else if (event === "error") throw Object.assign(new Error((payload as AnswerError).message), payload as AnswerError);
1449
+ }
1450
+ }
1451
+ throw new Error("The connection closed before the answer was complete. Ask again.");
1452
+ }
1453
+ ```
1454
+
1455
+ And a page that uses it, with a Stop button:
1456
+
1457
+ ```ts
1458
+ // askStreamed is the function above.
1459
+ const answerView = document.querySelector<HTMLElement>("#answer")!;
1460
+ const statusView = document.querySelector<HTMLElement>("#status")!;
1461
+ const stepsView = document.querySelector<HTMLElement>("#steps")!;
1462
+ const stopButton = document.querySelector<HTMLButtonElement>("#stop")!;
1463
+
1464
+ export async function showAnswer(sessionId: string, question: string): Promise<void> {
1465
+ const controller = new AbortController();
1466
+ stopButton.onclick = () => controller.abort(); // the server sees the connection close, and stops
1467
+ let answer = "";
1468
+ answerView.textContent = "";
1469
+ stepsView.replaceChildren();
1470
+ try {
1471
+ const end = await askStreamed(sessionId, question, {
1472
+ text: (delta) => {
1473
+ answer += delta;
1474
+ answerView.textContent = answer;
1475
+ statusView.textContent = "";
1476
+ },
1477
+ activity: (text) => {
1478
+ statusView.textContent = text;
1479
+ },
1480
+ step: (text) => {
1481
+ const line = document.createElement("li");
1482
+ line.textContent = text; // text, never HTML: it holds file names and search words
1483
+ stepsView.append(line);
1484
+ },
1485
+ }, controller.signal);
1486
+ statusView.textContent = "";
1487
+ if (!end.answered) {
1488
+ answerView.textContent = end.blockReason ? "This question was blocked by the model's safety filters." : "No answer this time. Ask again, or ask more precisely.";
1489
+ }
1490
+ } catch (error) {
1491
+ if (controller.signal.aborted) statusView.textContent = "Stopped.";
1492
+ else statusView.textContent = error instanceof Error ? error.message : String(error);
1493
+ if (answer) answerView.textContent = `${answer}\n\n(The answer was cut off.)`;
1494
+ }
1495
+ }
1496
+ ```
1497
+
1498
+ - **`answered: false`** means the text is no answer: a blocked prompt, a reply cut off before its
1499
+ first word, or an answer that had no text (empty, or a tool call) even when it was asked for once
1500
+ more. The text may be empty or hold only a remark from before a tool call. Show your own message
1501
+ in its place, as above, and do not store it as the assistant's turn.
1502
+ - **An error after some text** (`incomplete: true`, or a dropped connection) leaves the text that
1503
+ arrived. Keep it, mark it as cut off, and let the user ask again.
1504
+ - **Stop** aborts the `fetch`. The connection closes, the server aborts the question, and `fetch`'s
1505
+ reader rejects with an `AbortError`.
1506
+ - **A connection that drops** ends the stream without a `done` or `error` event, or makes a read
1507
+ fail. Either way the function throws: the question cannot be resumed.
1508
+
1509
+ ## The example server: `examples/server.ts`
1510
+
1511
+ The repository has a chat server in one file, with no dependencies beyond the package and its
1512
+ optional ones: the upload routes, a chat route that streams over Server-Sent Events, and a page.
1513
+ To run it, from a clone of the repository:
1514
+
1515
+ ```bash
1516
+ npm install && npm run build
1517
+ GEMINI_API_KEY=... node examples/server.ts # then open http://localhost:3000
1518
+ ```
1519
+
1520
+ It needs Node 22.18 or a later 22.x, or Node 23.6 or later (24, for example), which run TypeScript
1521
+ files directly. `npm install` also installs the optional dependencies, which the repository has as
1522
+ dev dependencies, so PDF, DOCX, PPTX and XLSX uploads work. `GEMINI_MODEL` names the model, and
1523
+ `GEMINI_EXPLORER_MODEL`, when set, an [explorer model](./explorer-model.md).
1524
+
1525
+ What it does:
1526
+
1527
+ - **The library.** `geminiApi()` with an API key for the endpoint, and `createLargeFiles` with a
1528
+ `FileDocumentStore` in `.data/large-files` and `keepOriginals: ["pdf"]`, so the model can look at
1529
+ the pages of a PDF ([PDFs](./pdfs.md)). To try Vertex AI, swap the endpoint for `vertexAi()`
1530
+ ([Gemini and Vertex AI](./vertex-and-gemini.md)).
1531
+ - **Uploads.** `createDocumentHandlers` on `node:http`: `POST /api/documents` to `upload`,
1532
+ `DELETE /api/documents/:id` to `remove`. `getOwner` returns `undefined`, so every upload is
1533
+ anonymous.
1534
+ - **The chat route.** `POST /api/chat` takes `{ chatId, question, documentIds }` as JSON, checked
1535
+ before the stream starts (`400` or `413` otherwise). The server keeps each chat's turns, tool
1536
+ rounds included, in a `Map` (for the demo only: in memory, the latest questions of the latest
1537
+ chats). The route calls `askStream` with the model, and the explorer when `GEMINI_EXPLORER_MODEL`
1538
+ names one, and passes the stream itself to `writeSseEvents`, so that the question stops as soon
1539
+ as the page goes away. Its `map` puts `run.error` in the app's own words, by `error.name` and
1540
+ `error.kind`. After the stream, it keeps `result.toolTurns` and the answer when there is one, or
1541
+ the `toolTurns` of `partialResultOf(error)`.
1542
+ - **The page.** A file input uploads with `fetch` (`application/octet-stream`, `X-File-Name`,
1543
+ `Accept: text/event-stream`), shows the ingest's progress, then the format, lines and estimated
1544
+ tokens of the summary in `ingest.finish`. A question is posted to `/api/chat`, and the events
1545
+ are read with a stream reader that splits them at blank lines, as
1546
+ [above](#reading-the-events-in-the-browser). The page shows a status line, a list of tool calls
1547
+ with a mark for each outcome and a counter for whole-file reads, the text as it streams, and the
1548
+ usage in `run.finish` or the message of `run.error`.
1549
+
1550
+ During the work on 0.7.0, the event stream was checked live against the Gemini API: the counts the
1551
+ events give, the roles of the requests of an explorer pair (`explorer` and `answer`), and this
1552
+ server's stream to the page, end to end.
1553
+
1554
+ It is a demo, kept short. Before you build on it, check your server against this list, which this
1555
+ guide covers:
1556
+
1557
+ - `getOwner` returns the signed-in user, and the chat route passes the same `owner`.
1558
+ - The JSON body is read and checked before the stream starts, and a bad one gets a `400`.
1559
+ - The page shows its own message when `answered` in `run.finish` is false.
1560
+ - `toolTurns` are kept on the server with each question, from `stream.result` or
1561
+ `partialResultOf(error)`, and passed back in the history. The page never handles them.
1562
+ - `eventResults` stays off, so no event carries the text of your documents.
1563
+ - `run.error` carries a message safe to show; map it to your own words by `kind` and `name` if you
1564
+ like. The provider's message is on the thrown error, for your log only.
1565
+ - The stream is passed to `writeSseEvents` itself, or the route stops the question when the
1566
+ response closes.
1567
+ - Keep-alive comments and a deadline keep long questions alive and bounded.
1568
+ - `files.sweep()` runs on a timer, so expired uploads leave the disk.
1569
+
1570
+ ## Reference
1571
+
1572
+ - [`llm-large-files/node`](../reference/node.md): `createDocumentHandlers`, `DocumentHandlerOptions`,
1573
+ `DocumentHandlers`, every route, status and body, the upload's events, and `writeSseEvents`,
1574
+ `sseMessageOf`, `SseMessage` and `SseWriteOptions`.
1575
+ - [The library](../reference/library.md): `IngestInput` (`onEvent`, `runId`), `toDocumentSummary`,
1576
+ `DocumentSummary`, `DocumentMeta`, `ProgressEvent`, `ToolOptions`.
1577
+ - [Events](../reference/events.md): `AskEvent`, `IngestEvent`, `EventError`, `EventResult`,
1578
+ `askStream`, `eventStream`, `streamText`, and how the callbacks map to events.
1579
+ - [The tool loop](../reference/ask.md): `askWithFiles`, `askStream`, `AskOptions` (`onEvent`,
1580
+ `streamText`, `eventResults`, `runId`, `onText`, `onActivity`, `onStep`, `signal`), `AskResult`,
1581
+ `partialResultOf`.
1582
+ - [`llm-large-files/gemini`](../reference/gemini.md): `askGemini` and its options.
1583
+ - [Errors, retries and streams](../reference/errors-and-retries.md): `ModelErrorKind`,
1584
+ `errorKindOf`, the default waits.
1585
+
1586
+ Related guides: [Conversations](./conversations.md) for the history and `toolTurns`,
1587
+ [An explorer model](./explorer-model.md) for the second model whose requests the events tell apart,
1588
+ [Errors and reliability](./errors-and-reliability.md) for every error and deadline,
1589
+ [Storage](./storage.md) for owners and sessions, [Deployment](./deployment.md) for several servers
1590
+ and proxies, and [Testing](./testing.md) for running these routes without a real model.