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