llm-large-files 0.8.1 → 0.9.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 +631 -0
- package/README.md +9 -10
- package/dist/access.d.ts +86 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +131 -0
- package/dist/access.js.map +1 -0
- package/dist/ask.d.ts +45 -1
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +181 -20
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +57 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +217 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +72 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +102 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +35 -9
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +14 -3
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +46 -35
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +19 -3
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +84 -12
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +18 -6
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +2 -0
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +70 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +868 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +176 -34
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +332 -512
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -2
- package/dist/limiter.js +2 -2
- package/dist/map-reduce.js +3 -3
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +43 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +63 -3
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +234 -7
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +482 -121
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +18 -3
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +102 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +365 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +4 -3
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +7 -6
- package/dist/node/sse.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/ranged.d.ts +22 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +50 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +120 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +582 -139
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +25 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +135 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +116 -13
- package/dist/types.d.ts.map +1 -1
- package/docs/README.md +17 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +12 -8
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +16 -7
- package/docs/guides/deployment.md +309 -87
- package/docs/guides/errors-and-reliability.md +161 -23
- package/docs/guides/own-adapter-and-loop.md +27 -10
- package/docs/guides/pdfs.md +123 -29
- package/docs/guides/storage.md +634 -143
- package/docs/guides/testing.md +78 -129
- package/docs/guides/vertex-and-gemini.md +10 -7
- package/docs/guides/web-app.md +322 -77
- package/docs/how-it-works.md +35 -8
- package/docs/measurements.md +63 -8
- package/docs/publishing.md +112 -36
- package/docs/reference/ask.md +154 -13
- package/docs/reference/errors-and-retries.md +166 -14
- package/docs/reference/events.md +53 -20
- package/docs/reference/gemini.md +70 -21
- package/docs/reference/library.md +709 -165
- package/docs/reference/node.md +633 -104
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +15 -5
- package/docs/security.md +316 -70
- package/docs/troubleshooting.md +165 -58
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +12 -3
- package/src/access.ts +144 -0
- package/src/ask.ts +230 -19
- package/src/cache.ts +20 -5
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +255 -0
- package/src/errors.ts +129 -15
- package/src/events.ts +86 -21
- package/src/evidence.ts +14 -3
- package/src/extract.ts +50 -33
- package/src/gemini/adapter.ts +97 -11
- package/src/gemini/chat.ts +20 -6
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +9 -6
- package/src/ingest.ts +927 -0
- package/src/library.ts +482 -523
- package/src/limiter.ts +2 -2
- package/src/map-reduce.ts +3 -3
- package/src/model.ts +69 -5
- package/src/node/handlers.ts +691 -117
- package/src/node/index.ts +13 -2
- package/src/node/ingest-child.ts +23 -5
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +365 -0
- package/src/node/sse.ts +7 -6
- package/src/pdf-layout.ts +69 -11
- package/src/ranged.ts +42 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/source.ts +178 -0
- package/src/stores.ts +635 -140
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +150 -14
- package/src/types.ts +106 -13
package/docs/guides/web-app.md
CHANGED
|
@@ -60,9 +60,9 @@ and never rejects, so you can call it without a `catch`, from `node:http` or fro
|
|
|
60
60
|
|
|
61
61
|
| Handler | Route it for | What it does |
|
|
62
62
|
|---|---|---|
|
|
63
|
-
| `upload(request, response)` | `POST` | Asks `getOwner` who is asking, reads the raw body up to `files.maxUploadBytes
|
|
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. |
|
|
63
|
+
| `upload(request, response)` | `POST` | Asks `getOwner` who is asking and `getScope` which chat it is for, asks `prepareUpload` for an ID and where to save the body, reads the raw body up to `files.maxUploadBytes` (into memory, or into a file), ingests it with that owner and scope, calls `onUploaded`, 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 or another chat's. |
|
|
65
|
+
| `remove(request, response, id)` | `DELETE` | Deletes the document, its text and any kept original, calls `onRemoved`, and answers `200` with `{ "deleted": true }`, or `{ "deleted": false }` when this owner had no such document in this chat. |
|
|
66
66
|
|
|
67
67
|
The handlers do not check the method or the path. Route each request to the one you mean.
|
|
68
68
|
|
|
@@ -159,7 +159,10 @@ either. The handlers call it before they read the body, so a refused upload is n
|
|
|
159
159
|
`{ "error": "Upload failed (empty owner)." }` before its body is read. An owner that is neither a
|
|
160
160
|
string nor a finite number (`req.user` in place of `req.user.id`, say) is answered
|
|
161
161
|
`{ "error": "Upload failed (owner is not a string)." }`. `get` and `remove` pass such an owner on
|
|
162
|
-
as before
|
|
162
|
+
as before, except under `requireOwner`, where they answer `""` or spaces only with a `500` too:
|
|
163
|
+
"The file could not be looked up (empty owner)." for `get`, "The file could not be deleted
|
|
164
|
+
(empty owner)." for `remove`. Under `requireOwner`, `null` is a `401` on every route, as
|
|
165
|
+
`undefined`. Where every upload needs a user, throw an error with `status: 401` when there is
|
|
163
166
|
none, as the example above does. Return `undefined` only where anonymous uploads are meant, and
|
|
164
167
|
write `user?.id || undefined` there, not `user?.id ?? ""`: a header that arrives empty gives `""`
|
|
165
168
|
too.
|
|
@@ -167,11 +170,213 @@ either. The handlers call it before they read the body, so a refused upload is n
|
|
|
167
170
|
package makes them: the handler answers with that status and the error's message, as the `401`
|
|
168
171
|
above. Any other error is answered `500`, without its message, which may name your hosts.
|
|
169
172
|
|
|
173
|
+
- **Under `requireOwner`** (new in 0.9.0): when the library is made with `requireOwner: true`,
|
|
174
|
+
`createDocumentHandlers` throws a `TypeError` without `getOwner`, and an owner of `undefined`, or
|
|
175
|
+
`null` (`req.user?.id ?? null`), is answered `401` `{ "error": "Sign in first." }` on every route,
|
|
176
|
+
before the body is read. No document is then ever anyone's.
|
|
177
|
+
|
|
170
178
|
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`.
|
|
172
|
-
chat
|
|
173
|
-
|
|
174
|
-
|
|
179
|
+
or `askWithFiles`, and to `files.getMeta`, `files.getOriginal` and `files.delete`. To keep each
|
|
180
|
+
chat's files apart, give the chat as a scope with `getScope` (below). See [Storage](./storage.md),
|
|
181
|
+
and [Security](../security.md) for what ownership does and does not protect.
|
|
182
|
+
|
|
183
|
+
### Which chat an upload is for: `getScope`
|
|
184
|
+
|
|
185
|
+
New in 0.9.0. `getScope(request)` returns the scope of the request, such as `[userId, chatId]`, or
|
|
186
|
+
`undefined`. The handlers call it after `getOwner`, before they read the body. The upload is stored
|
|
187
|
+
in that scope, and `get` and `remove` find only the documents of the same scope: a file of another
|
|
188
|
+
chat answers as one that does not exist. With a scoped `FileDocumentStore`, the scope is also the
|
|
189
|
+
folder on disk ([Storage](./storage.md)).
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
import { createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
193
|
+
import { createDocumentHandlers } from "llm-large-files/node";
|
|
194
|
+
|
|
195
|
+
const files = createLargeFiles({
|
|
196
|
+
store: new FileDocumentStore("/data", { scopes: { depth: 2 } }), // /data/<user>/<chat>/.llm-large-files/
|
|
197
|
+
requireOwner: true,
|
|
198
|
+
requireScope: true,
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
const documents = createDocumentHandlers(files, {
|
|
202
|
+
getOwner: (request) => currentUserId(request),
|
|
203
|
+
// The chat comes from your route or a header. Check that it is the user's: throw a 404 if not.
|
|
204
|
+
getScope: async (request) => {
|
|
205
|
+
const userId = currentUserId(request)!;
|
|
206
|
+
const chatId = String(request.headers["x-chat-id"] ?? "");
|
|
207
|
+
if (!(await chats.belongsTo(chatId, userId))) throw Object.assign(new Error("This chat no longer exists."), { status: 404 });
|
|
208
|
+
return [userId, chatId];
|
|
209
|
+
},
|
|
210
|
+
});
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
- **A scope that is not valid** (not an array of 1 to 8 strings, or a segment with `/` or a
|
|
214
|
+
control character) is the server's mistake: `500` `{ "error": "Upload failed (invalid scope)." }`.
|
|
215
|
+
A scoped `FileDocumentStore` takes only safe segments: lowercase letters, digits, `_` and `-`
|
|
216
|
+
(`isSafeScopeSegment`), or a `hashedScopeSegment` of any ID.
|
|
217
|
+
- **No scope under `requireScope`** is `500` `{ "error": "Upload failed (no scope)." }`, and
|
|
218
|
+
`createDocumentHandlers` throws a `TypeError` without `getScope`.
|
|
219
|
+
- **A chat that was deleted.** With a scoped `FileDocumentStore` and `createScopeFolders` off (the
|
|
220
|
+
default), an upload into a chat whose folder your app removed is answered `404`
|
|
221
|
+
`{ "error": "This chat no longer exists." }`, and nothing is written.
|
|
222
|
+
- **A thrown error with a status** is answered with that status and its message, as for `getOwner`.
|
|
223
|
+
|
|
224
|
+
Pass the same scope to `askWithFiles` or `askGemini` (`scope`).
|
|
225
|
+
|
|
226
|
+
### Record each upload: `onUploaded` and `onRemoved`
|
|
227
|
+
|
|
228
|
+
New in 0.9.0. Your app usually keeps the files of a chat in its own database, with the chat.
|
|
229
|
+
`onUploaded` records each upload there in the same request: it is called once the file is stored,
|
|
230
|
+
before the answer, and the answer waits for it. `onRemoved` is called after `remove` deleted a
|
|
231
|
+
document.
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
const documents = createDocumentHandlers(files, {
|
|
235
|
+
getOwner: (request) => currentUserId(request),
|
|
236
|
+
getScope: (request) => [currentUserId(request)!, String(request.headers["x-chat-id"])],
|
|
237
|
+
onUploaded: async (document, { scope, clientGone }) => {
|
|
238
|
+
// Throw to fail the upload: the document is deleted, and the browser gets the error.
|
|
239
|
+
const file = await chats.addFile(scope![1]!, { documentId: document.id, name: document.name, sha256: document.sha256, clientGone });
|
|
240
|
+
return { answer: { fileNumber: file.number } }; // added to the 201, or ingest.finish.app
|
|
241
|
+
},
|
|
242
|
+
onRemoved: (id, { scope }) => chats.removeFile(scope![1]!, id),
|
|
243
|
+
});
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
- **`document`** is the whole `DocumentMeta`, with its owner and scope: for the server only. The
|
|
247
|
+
browser gets the summary.
|
|
248
|
+
- **What it returns.** `{ answer }` adds the answer's fields to the `201` JSON (the summary's own
|
|
249
|
+
fields win), and is `app` in the `ingest.finish` event of an upload with progress. Return
|
|
250
|
+
nothing to add nothing.
|
|
251
|
+
- **When it throws**, the document is deleted, and the upload is answered with the error's status
|
|
252
|
+
(400 to 599) and message, or `500` `{ "error": "Upload failed." }`.
|
|
253
|
+
- **No time limit.** The answer waits for the hook as long as it runs: give your database calls a
|
|
254
|
+
timeout of their own. The upload's room (`maxPendingUploadBytes`) is given back, and the body the
|
|
255
|
+
handler read is freed, before the hook is called, so a slow hook does not hold up other uploads.
|
|
256
|
+
- **`clientGone`** is `true` when the browser went away before the hook ran: the file was stored
|
|
257
|
+
all the same. Record it, or delete it, as your app needs. A browser that leaves before the
|
|
258
|
+
ingest ends leaves nothing stored, and the hook is not called. So `clientGone` is for a browser
|
|
259
|
+
that left after the ingest ended, or for an `ingest` of your own that does not stop on its
|
|
260
|
+
`signal`.
|
|
261
|
+
- **`onRemoved`** runs only for `{ "deleted": true }`. When it throws, `remove` answers its error;
|
|
262
|
+
the document is deleted all the same.
|
|
263
|
+
|
|
264
|
+
[The node reference](../reference/node.md#the-hooks-onuploaded-and-onremoved) has every detail.
|
|
265
|
+
|
|
266
|
+
### Save each upload where you keep it: `prepareUpload`
|
|
267
|
+
|
|
268
|
+
New in 0.9.0. When your app keeps the uploads of a chat in its folder anyway (to show a file
|
|
269
|
+
again, or to ingest it again later), let the handler save the body there, once, as it arrives.
|
|
270
|
+
`prepareUpload` runs before the body is read, and returns the document's ID, the path of the file
|
|
271
|
+
and its ref. The file is then ingested from that path, and kept by reference: `view_pages` reads it
|
|
272
|
+
there through `fileOriginals`, and the store keeps no second copy.
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
// documents.ts: each upload saved once as /data/<user>/<chat>/uploads/<id>, beside the store's files.
|
|
276
|
+
import { randomUUID } from "node:crypto";
|
|
277
|
+
import { rm } from "node:fs/promises";
|
|
278
|
+
import path from "node:path";
|
|
279
|
+
import { createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
280
|
+
import { createDocumentHandlers, fileOriginals } from "llm-large-files/node";
|
|
281
|
+
|
|
282
|
+
const VOLUME = "/data";
|
|
283
|
+
|
|
284
|
+
export const files = createLargeFiles({
|
|
285
|
+
store: new FileDocumentStore(VOLUME, { scopes: { depth: 2 } }), // /data/<user>/<chat>/.llm-large-files/
|
|
286
|
+
keepOriginals: ["pdf"],
|
|
287
|
+
originals: fileOriginals(VOLUME), // reads the uploads back by their ref
|
|
288
|
+
ttlMs: Infinity, // the documents stay as long as the chat, as its uploads do
|
|
289
|
+
requireOwner: true,
|
|
290
|
+
requireScope: true,
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
export const documents = createDocumentHandlers(files, {
|
|
294
|
+
getOwner: (request) => currentUserId(request),
|
|
295
|
+
getScope: async (request) => {
|
|
296
|
+
const userId = currentUserId(request)!;
|
|
297
|
+
const chatId = String(request.headers["x-chat-id"] ?? "");
|
|
298
|
+
if (!(await chats.belongsTo(chatId, userId))) throw Object.assign(new Error("This chat no longer exists."), { status: 404 });
|
|
299
|
+
return [userId, chatId];
|
|
300
|
+
},
|
|
301
|
+
// Before the body is read: the upload's ID, where its body goes, and the ref fileOriginals reads.
|
|
302
|
+
prepareUpload: (_request, { scope }) => {
|
|
303
|
+
const id = `up-${randomUUID().replaceAll("-", "")}`;
|
|
304
|
+
const ref = [...scope!, "uploads", id].join("/"); // <user>/<chat>/uploads/<id>
|
|
305
|
+
return { id, path: path.join(VOLUME, ref), original: { ref } };
|
|
306
|
+
},
|
|
307
|
+
// Once it is stored: the chat lists it. Throw, and the document and the file are removed.
|
|
308
|
+
onUploaded: async (document, { scope }) => {
|
|
309
|
+
await chats.addFile(scope![1]!, { documentId: document.id, name: document.name, sha256: document.sha256 });
|
|
310
|
+
},
|
|
311
|
+
// The library never removes the file it was read from: remove it with the document.
|
|
312
|
+
onRemoved: async (id, { scope }) => {
|
|
313
|
+
await chats.removeFile(scope![1]!, id);
|
|
314
|
+
await rm(path.join(VOLUME, ...scope!, "uploads", id), { force: true });
|
|
315
|
+
},
|
|
316
|
+
});
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
- **The folders are yours.** The handler makes no folder: make `<user>/<chat>/uploads` when the chat
|
|
320
|
+
is made, with `mode: 0o700`. A folder that is not there is answered `500`
|
|
321
|
+
`{ "error": "Upload failed (ENOENT)." }`; a chat that was deleted should be refused in
|
|
322
|
+
`getScope`, with a `404`, as above. Removing the chat's folder removes the store's files and the
|
|
323
|
+
uploads together ([Storage](./storage.md#files-in-a-folder-per-user-or-per-chat)).
|
|
324
|
+
- **No links below `/data`.** `fileOriginals` does not read a file through a link in its folders
|
|
325
|
+
(`uploads` pointing to another disk, say). So the handler refuses such a path before it writes:
|
|
326
|
+
`500` `{ "error": "Upload failed (ELOOP)." }`. `/data` itself may be a link. Mount another disk
|
|
327
|
+
there rather than link to it: a mount is not a link.
|
|
328
|
+
- **Kept as long as the chat.** `ttlMs: Infinity`: a document that expires is removed without a
|
|
329
|
+
call to `onRemoved`, and would leave its upload and the chat's record behind. Remove the
|
|
330
|
+
documents with their chat ([Storage](./storage.md#files-in-a-folder-per-user-or-per-chat)).
|
|
331
|
+
- **Safe names.** The user and chat IDs are the scope's segments, and the folder names: lowercase
|
|
332
|
+
letters, digits, `_` and `-`. For other IDs, name both folders with `hashedScopeSegment`, as the
|
|
333
|
+
store does. Never build the path from the file's name: it is the client's.
|
|
334
|
+
- **The file is made new**, with `"wx"` and mode `0o600` (`uploadFileMode`; `0o640` when pods of
|
|
335
|
+
another user read the volume through a group). A file or a link already at the path is never
|
|
336
|
+
written through: the upload gets `409` `{ "error": "A file is already saved for this upload." }`.
|
|
337
|
+
- **It stays once the document is stored,** and `onUploaded` is told its `path`. **It is removed
|
|
338
|
+
when the upload fails**, whatever the reason: too large, a body that stops, a browser that leaves
|
|
339
|
+
before the ingest ends, a full disk (`503` with `Retry-After`), a disk that does not answer within
|
|
340
|
+
`uploadIdleTimeoutMs` (`500` "Upload failed (ETIMEDOUT)."), a file that cannot be read, an ID
|
|
341
|
+
that is taken, or `onUploaded` throwing. A server that is killed in the middle of an upload
|
|
342
|
+
cannot remove it, and nothing else does: remove such files with a job of your own
|
|
343
|
+
([Deployment](./deployment.md#stopping-a-server)).
|
|
344
|
+
- **No memory.** The body is written as it arrives, and read again when the ingest's turn comes: it
|
|
345
|
+
is not held while it waits, and takes no room of `maxPendingUploadBytes`.
|
|
346
|
+
- **Nothing of it reaches the browser or the model.** The path and the ref are kept in the metadata,
|
|
347
|
+
for the server.
|
|
348
|
+
- **Without a path,** `prepareUpload` can still give the ID alone: `return { id }`.
|
|
349
|
+
|
|
350
|
+
Every rule is in the [node reference](../reference/node.md#saving-the-body-prepareupload).
|
|
351
|
+
|
|
352
|
+
### Large uploads off the heap: `uploadSpool`
|
|
353
|
+
|
|
354
|
+
New in 0.9.0. Without a path from `prepareUpload`, the handler holds each body in memory while it is
|
|
355
|
+
ingested. `uploadSpool` writes the larger ones to a temporary file instead:
|
|
356
|
+
|
|
357
|
+
```ts
|
|
358
|
+
const documents = createDocumentHandlers(files, {
|
|
359
|
+
getOwner: (request) => currentUserId(request),
|
|
360
|
+
uploadSpool: { directory: "/var/spool/uploads" }, // this server's own folder, on a disk
|
|
361
|
+
});
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
- **Which bodies.** Those over `minBytes` (1 MiB by default), and those without a `Content-Length`.
|
|
365
|
+
Smaller ones stay in memory. `uploadSpool: true` takes the defaults, with `os.tmpdir()`.
|
|
366
|
+
- **The file** is made new (`"wx"`), with a random name and mode `0o600`, ingested from its path, and
|
|
367
|
+
removed once the ingest ends, whatever the end. `onUploaded` runs after, without a path.
|
|
368
|
+
- **Room.** `maxSpooledUploadBytes` (ten times `maxUploadBytes`) bounds the spool's files at once:
|
|
369
|
+
past it, and on a full disk, the upload gets `503` with `Retry-After`. A disk that does not answer
|
|
370
|
+
within `uploadIdleTimeoutMs` gets `500` "Upload failed (ETIMEDOUT).", and gives the room back.
|
|
371
|
+
`maxPendingUploadBytes` then counts only the bodies held in memory, so several uploads sent
|
|
372
|
+
without a `Content-Length` no longer fill it.
|
|
373
|
+
- **Where.** On a disk, not a memory-backed folder, which would take the memory back
|
|
374
|
+
([Deployment](./deployment.md#uploads-and-ingest)). A server that stops in the middle of an upload
|
|
375
|
+
leaves its file. So give each server process a folder of its own (a disk-backed `emptyDir`, or
|
|
376
|
+
`path.join("/data/spool", os.hostname())` on the shared volume; both are one a pod, so with
|
|
377
|
+
several server processes in a pod add a number of each), and empty it when that server starts.
|
|
378
|
+
Never empty a folder that several servers share: the uploads still arriving or waiting for their
|
|
379
|
+
turn would lose their files, and fail.
|
|
175
380
|
|
|
176
381
|
### What the browser sends
|
|
177
382
|
|
|
@@ -182,8 +387,9 @@ ownership does and does not protect.
|
|
|
182
387
|
line and paragraph separators and text-direction controls become a space, and most characters
|
|
183
388
|
that show nothing are removed (variation selectors and joiners stay): the name is shown to the
|
|
184
389
|
model and in your UI.
|
|
185
|
-
- **`X-File-Type`** is the MIME type, and is optional.
|
|
186
|
-
|
|
390
|
+
- **`X-File-Type`** is the MIME type, and is optional. It is URI-decoded. Without it,
|
|
391
|
+
`Content-Type` is taken as it came (not decoded, since 0.9.0), unless it is
|
|
392
|
+
`application/octet-stream`. The format comes from the extension first (`.log`, `.md`,
|
|
187
393
|
`.json`, `.csv`, `.pdf`, `.docx`, `.pptx` and a few more), then from the MIME type; anything else
|
|
188
394
|
is text, and text that looks like a log becomes a log. A text file needs no charset: one that is
|
|
189
395
|
not UTF-8 is read in the older encoding of Hebrew, Arabic, Cyrillic, Japanese or Western European
|
|
@@ -209,24 +415,32 @@ UTF-8, `encoding` names the older encoding it was read in (`"windows-1255"`), an
|
|
|
209
415
|
Your page can show "read as windows-1255", or warn that some characters could not be read and ask
|
|
210
416
|
for the file saved as UTF-8.
|
|
211
417
|
|
|
418
|
+
`onUploaded`'s `answer`, when it returns one, adds its fields to it.
|
|
419
|
+
|
|
212
420
|
Everything else is JSON `{ "error": "…" }`, with a message you can show: `400` for a missing name or
|
|
213
|
-
a body another middleware already parsed, `
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
`
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
The
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
421
|
+
a body another middleware already parsed, `401` "Sign in first." under `requireOwner`, `404` "This
|
|
422
|
+
chat no longer exists." for a chat whose folder is gone, `413` over `maxUploadBytes`, `422` for a
|
|
423
|
+
file that cannot be read, `409` "A file is already saved for this upload." when a file is already at the
|
|
424
|
+
path of `prepareUpload`, `503` with `Retry-After` when the server holds as many uploads as it
|
|
425
|
+
takes at once, its readers are busy, its disk is full, or the store failed (send the file again
|
|
426
|
+
after `Retry-After` seconds), `408` for a body that stopped arriving, an error's own status (400 to 599) from
|
|
427
|
+
`getOwner`, `getScope`, `prepareUpload`, `onUploaded` or an extractor, and `500` for a failure of the server, among
|
|
428
|
+
them `Upload failed (empty owner).`, `Upload failed (owner is not a string).`,
|
|
429
|
+
`Upload failed (invalid scope).` and `Upload failed.`. `get` answers `404` for a document this owner
|
|
430
|
+
cannot see in this chat, and `get` and `remove` answer `503` when the store cannot be read. Every
|
|
431
|
+
status and body is in the [node reference](../reference/node.md#uploadrequest-response).
|
|
432
|
+
|
|
433
|
+
The rule is `uploadAnswerOf` from `llm-large-files/node`
|
|
434
|
+
([reference](../reference/node.md#how-errors-are-answered)). Since 0.9.0, only an `IngestError` is a
|
|
435
|
+
`422` with its message, and a file of code `"unreadable"` gets fixed words instead ("This file could
|
|
436
|
+
not be read. It may be damaged, or not of the type its name says."): its own message is a parser's,
|
|
437
|
+
or an extractor's of your own, which may name a host. A store that fails while it writes is a `DocumentStoreError`: `503`,
|
|
438
|
+
`Retry-After: 5`, and words that name no path or host. Any other error without a status is a `500`
|
|
439
|
+
"Upload failed.", without its message, which may name your hosts: a `LargeFiles` of your own whose
|
|
440
|
+
`ingest` throws a plain `Error` is answered so, and should throw `new IngestError(code, message)` for
|
|
441
|
+
a file it refuses, as `ingestInProcess` in [Deployment](./deployment.md#uploads-and-ingest) does.
|
|
442
|
+
The handlers log nothing: log the error in your store, or in your `ingest`, before you throw it.
|
|
443
|
+
See [Storage](./storage.md#errors).
|
|
230
444
|
|
|
231
445
|
## Uploads through your own route
|
|
232
446
|
|
|
@@ -246,9 +460,10 @@ input, an [`IngestInput`](../reference/library.md#ingestinput):
|
|
|
246
460
|
| Field | What it is |
|
|
247
461
|
|---|---|
|
|
248
462
|
| `name` | The file's name. Cleaned as above. |
|
|
249
|
-
| `mimeType` | Optional. Used for the format when the extension says nothing. |
|
|
250
|
-
| `bytes` | The file, as a `Uint8Array`. A Node `Buffer` is one. |
|
|
251
|
-
| `owner` | Optional. The user (or tenant
|
|
463
|
+
| `mimeType` | Optional. Used for the format when the extension says nothing. Kept as its type and subtype, in lower case, without parameters (0.9.0). |
|
|
464
|
+
| `bytes` | The file, as a `Uint8Array`. A Node `Buffer` is one. Since 0.9.0, give `source: { path }` in its place for a file your route saved to disk: it is read at the ingest's turn ([`IngestFromSource`](../reference/library.md#ingestfromsource)). |
|
|
465
|
+
| `owner` | Optional. The user (or tenant) 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 `500` "Upload failed.". |
|
|
466
|
+
| `scope` | Optional. The chat the document belongs to, such as `[userId, chatId]`. New in 0.9.0. |
|
|
252
467
|
| `signal` | Optional. Stops the ingest when it aborts, for example when the uploader goes away: `ingest` throws its `reason`, and nothing is stored. |
|
|
253
468
|
|
|
254
469
|
Answer the browser with `toDocumentSummary(meta)`, not with `meta`: the summary holds the fields that
|
|
@@ -260,38 +475,35 @@ the cases of the `422` above (an empty, binary or compressed file, no text, a mi
|
|
|
260
475
|
dependency, a file past `maxTextBytes` or `maxPdfPages`, one that took longer than
|
|
261
476
|
`ingestTimeoutMs`), and a file larger than `maxUploadBytes` ("app.log is larger than the 100 MB
|
|
262
477
|
upload limit."). [PDFs and other formats](./pdfs.md#what-is-refused) lists every message. A store
|
|
263
|
-
that fails while it writes
|
|
264
|
-
|
|
478
|
+
that fails while it writes is a `DocumentStoreError` since 0.9.0, with status 503, a message that
|
|
479
|
+
names no path or host, and the store's error as `cause` (it threw the store's error as it came).
|
|
480
|
+
`uploadAnswerOf` from `llm-large-files/node` (new in 0.9.0) tells them apart by the rule
|
|
481
|
+
`createDocumentHandlers` uses. This helper adds a line in your log for the server's failures:
|
|
265
482
|
|
|
266
483
|
```ts
|
|
267
484
|
// ingest-failure.ts
|
|
485
|
+
import { uploadAnswerOf, type UploadAnswer } from "llm-large-files/node";
|
|
486
|
+
|
|
268
487
|
/**
|
|
269
|
-
* The status and message for an error of files.ingest,
|
|
270
|
-
*
|
|
271
|
-
*
|
|
272
|
-
*
|
|
273
|
-
* a store's write error that has no status and no system error code with 422 and its message.
|
|
488
|
+
* The status and message for an error of files.ingest, as createDocumentHandlers answers it: a file
|
|
489
|
+
* that cannot be read (an IngestError) is the client's 422 (413, 409, or 503 for "busy") with its
|
|
490
|
+
* message; a store that failed is a 503 to try again; any other error is the server's 500
|
|
491
|
+
* "Upload failed.", without its message, which may name your hosts.
|
|
274
492
|
*/
|
|
275
|
-
export function ingestFailure(error: unknown):
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
return { status: value, error: error.message || "Upload failed." };
|
|
280
|
-
}
|
|
281
|
-
if (typeof code === "string" && typeof syscall === "string") return { status: 500, error: `Upload failed (${code}).` };
|
|
282
|
-
if (!(error instanceof Error)) return { status: 500, error: "Upload failed." };
|
|
283
|
-
return { status: 422, error: error.message };
|
|
493
|
+
export function ingestFailure(error: unknown): UploadAnswer {
|
|
494
|
+
const answer = uploadAnswerOf(error);
|
|
495
|
+
if (answer.status >= 500) console.error("An upload failed", error); // the error itself, for your log
|
|
496
|
+
return answer;
|
|
284
497
|
}
|
|
285
498
|
```
|
|
286
499
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
100 MB upload limit."), and this helper with the error's own message.
|
|
500
|
+
A store that failed reaches the helper as a `DocumentStoreError`: `503`, with `retryAfterMs` 5,000.
|
|
501
|
+
Send it as `Retry-After`, in seconds. Pass the `DocumentStoreError` on as it is: an error of your
|
|
502
|
+
own thrown in its place is answered `500` ([Storage](./storage.md#errors)). One thing differs from
|
|
503
|
+
the handler: a `413` keeps the error's own message ("app.log is larger than the 100 MB upload
|
|
504
|
+
limit."), where the handler says "The file is larger than the 100 MB upload limit.". To answer in
|
|
505
|
+
your users' language, word the error with
|
|
506
|
+
[`errorInfoOf`](./errors-and-reliability.md#your-users-words-errorinfoof) instead.
|
|
295
507
|
|
|
296
508
|
Check the size before you call `ingest`, and refuse with `413` while you read: `ingest` checks it
|
|
297
509
|
too, but only once the whole file is in memory.
|
|
@@ -386,6 +598,9 @@ export function formUploadRoute(addDocument: (sessionId: string, userId: string,
|
|
|
386
598
|
}
|
|
387
599
|
```
|
|
388
600
|
|
|
601
|
+
`createDocumentHandlers` does the same for a raw upload with `getScope` and `onUploaded`
|
|
602
|
+
([above](#record-each-upload-onuploaded-and-onremoved)).
|
|
603
|
+
|
|
389
604
|
- `defParamCharset: "utf8"` reads file names that are not ASCII (Hebrew, Chinese) as the browser
|
|
390
605
|
sent them. busboy's own default is Latin-1.
|
|
391
606
|
- `fileSize: limit + 1` makes busboy cut the file one byte past the limit, which is how the size
|
|
@@ -417,6 +632,8 @@ export async function uploadFromRequest(request: Request, owner: string): Promis
|
|
|
417
632
|
// Not URI-encoded: keep it as it came.
|
|
418
633
|
}
|
|
419
634
|
if (!name.trim()) return Response.json({ error: "Name the file with an X-File-Name header." }, { status: 400 });
|
|
635
|
+
// This route reads the body before ingest: bound the bytes it holds at once yourself, as
|
|
636
|
+
// createDocumentHandlers does with maxPendingUploadBytes (Deployment, Uploads and ingest).
|
|
420
637
|
|
|
421
638
|
const tooLarge = { error: "The file is larger than the upload limit." };
|
|
422
639
|
if (Number(request.headers.get("content-length")) > files.maxUploadBytes) return Response.json(tooLarge, { status: 413 });
|
|
@@ -506,7 +723,7 @@ import type { DocumentSummary } from "llm-large-files";
|
|
|
506
723
|
|
|
507
724
|
/** Sends one file to POST /api/documents. Throws with a message you can show. */
|
|
508
725
|
export async function uploadFile(file: File): Promise<DocumentSummary> {
|
|
509
|
-
const
|
|
726
|
+
const send = () => fetch("/api/documents", {
|
|
510
727
|
method: "POST",
|
|
511
728
|
headers: {
|
|
512
729
|
"Content-Type": "application/octet-stream",
|
|
@@ -515,6 +732,13 @@ export async function uploadFile(file: File): Promise<DocumentSummary> {
|
|
|
515
732
|
},
|
|
516
733
|
body: file,
|
|
517
734
|
});
|
|
735
|
+
let response = await send();
|
|
736
|
+
// A busy server (503) says when to try again: twice more, then its message is shown.
|
|
737
|
+
for (let attempt = 0; response.status === 503 && attempt < 2; attempt++) {
|
|
738
|
+
const seconds = Number(response.headers.get("retry-after")) || 5;
|
|
739
|
+
await new Promise((resolve) => setTimeout(resolve, seconds * 1_000));
|
|
740
|
+
response = await send();
|
|
741
|
+
}
|
|
518
742
|
// An error page of a proxy (a 413 or a 502) is not JSON: the status then makes the message.
|
|
519
743
|
const result = (await response.json().catch(() => ({}))) as Partial<DocumentSummary> & { error?: string };
|
|
520
744
|
if (!response.ok || !result.id) throw new Error(result.error ?? `The upload failed (HTTP ${response.status}).`);
|
|
@@ -539,7 +763,7 @@ export async function uploadFile(file: File): Promise<DocumentSummary> {
|
|
|
539
763
|
New in 0.7.0. A large PDF or DOCX can take a while to read once it has arrived. Send the same
|
|
540
764
|
request with `Accept: text/event-stream`, and `upload` answers with the ingest's events as
|
|
541
765
|
Server-Sent Events: how far each stage is, then the summary. The checks that run before the ingest
|
|
542
|
-
(the name, `getOwner`, a body already parsed, the size) still answer with their status and JSON, so
|
|
766
|
+
(the name, `getOwner`, `getScope`, a body already parsed, the size, the room for uploads held at once) still answer with their status and JSON, so
|
|
543
767
|
read the response as JSON when it is not `200`:
|
|
544
768
|
|
|
545
769
|
```ts
|
|
@@ -600,10 +824,16 @@ export async function uploadWithProgress(file: File, onProgress: (text: string)
|
|
|
600
824
|
at most about every 12 ms, and once more when it ends. Not every file goes through every stage,
|
|
601
825
|
and a stage with nothing to report may send nothing.
|
|
602
826
|
- **The stream ends with one `ingest.finish` or one `ingest.error`.** `ingest.finish` holds in
|
|
603
|
-
`document` the summary a `201` holds
|
|
604
|
-
|
|
605
|
-
message
|
|
606
|
-
|
|
827
|
+
`document` the summary a `201` holds, and in `app` the `answer` of `onUploaded`, when it returned
|
|
828
|
+
one (new in 0.9.0). It comes once `onUploaded` is done. `ingest.error` holds in `error` the
|
|
829
|
+
`message` and `status` the JSON answer would have: `422` and "This file looks binary, not text.
|
|
830
|
+
…", say, or what `onUploaded` threw. A store's own message is never in it. Since 0.9.0 it also
|
|
831
|
+
has the `name` of a store that failed or of a scope error, the scope's `code`
|
|
832
|
+
(`"scope_missing"` for a deleted chat), and the `kind` of a model's error, so that `errorInfoOf`
|
|
833
|
+
reads it on your server.
|
|
834
|
+
- **Closing the page stops the ingest**, as it does for a JSON upload: nothing is stored. A file
|
|
835
|
+
stored before the page closed (the ingest had ended, and the events were still on their way)
|
|
836
|
+
still goes to `onUploaded`, with `clientGone: true`.
|
|
607
837
|
- **A wildcard does not ask for events.** `Accept: */*` or `text/*` keeps the `201` and JSON, and so
|
|
608
838
|
does `q=0`. The rules are in the [node reference](../reference/node.md#upload-with-progress-accept-textevent-stream).
|
|
609
839
|
|
|
@@ -834,7 +1064,7 @@ Between events, a comment line `: keep-alive` comes every 15 seconds. The events
|
|
|
834
1064
|
| `tool.progress` | `callId`, `stage` (`"map"` or `"reduce"`), `done`, `total`, `message` | A whole-file read: a counter on that call's line, and the status line: `message` and "…". |
|
|
835
1065
|
| `tool.end` | `callId`, `outcome` (`"ok"`, `"error"`, `"refused"`, `"already_shown"`, `"not_run"`), `ms`, `step`, `evidence`, `error` | The call's line, done: `step`, with a mark for the outcome. `step` is what `onStep` gets; it is absent for `"not_run"` and for a call ended because its turn failed. |
|
|
836
1066
|
| `text` | `delta`, `requestId` | The answer, growing. The deltas add up to the result's `text`. |
|
|
837
|
-
| `notice` | `code`, `message`, `display` | `display` `"activity"`: the status line. `"step"`: a line in the list. `"none"`: notices earlier versions did not show, such as `budget_reached` and `blocked`; show them if you like. |
|
|
1067
|
+
| `notice` | `code`, `message`, `display`, `documentIds` | `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. New in 0.9.0: `documents_missing` (files left out of the question, `onMissingDocuments: "drop"`), `document_gone` and `page_looks_busy`, with the files' IDs in `documentIds`: map them to the names you show. |
|
|
838
1068
|
| `retry` | `requestId`, `attempt`, `delayMs`, `error`, `message` | The status line: `message` ("The model did not answer (HTTP 503). Trying again in 2 s…"). |
|
|
839
1069
|
| `request.start`, `request.end` | `requestId`, `role`, `purpose`, `model`, `turn`; `ms`, `outcome`, `usage`, `error` | Usually not shown. For your logs and timings. |
|
|
840
1070
|
| `run.finish` | `result` (below) | The summary under the answer. Last. |
|
|
@@ -1510,33 +1740,43 @@ export async function showAnswer(sessionId: string, question: string): Promise<v
|
|
|
1510
1740
|
|
|
1511
1741
|
The repository has a chat server in one file, with no dependencies beyond the package and its
|
|
1512
1742
|
optional ones: the upload routes, a chat route that streams over Server-Sent Events, and a page.
|
|
1513
|
-
To run it, from a clone of the
|
|
1743
|
+
It is not for production as is: it has no sign-in (see below). To run it, from a clone of the
|
|
1744
|
+
repository:
|
|
1514
1745
|
|
|
1515
1746
|
```bash
|
|
1516
1747
|
npm install && npm run build
|
|
1517
|
-
GEMINI_API_KEY=... node examples/server.ts # then open http://
|
|
1748
|
+
GEMINI_API_KEY=... node examples/server.ts # then open http://127.0.0.1:3000
|
|
1518
1749
|
```
|
|
1519
1750
|
|
|
1520
1751
|
It needs Node 22.18 or a later 22.x, or Node 23.6 or later (24, for example), which run TypeScript
|
|
1521
1752
|
files directly. `npm install` also installs the optional dependencies, which the repository has as
|
|
1522
1753
|
dev dependencies, so PDF, DOCX, PPTX and XLSX uploads work. `GEMINI_MODEL` names the model, and
|
|
1523
|
-
`GEMINI_EXPLORER_MODEL`, when set, an [explorer model](./explorer-model.md).
|
|
1754
|
+
`GEMINI_EXPLORER_MODEL`, when set, an [explorer model](./explorer-model.md). It listens on
|
|
1755
|
+
`127.0.0.1` only, port 3000; `HOST` and `PORT` change that. Set `HOST=0.0.0.0` only behind a
|
|
1756
|
+
sign-in of your own.
|
|
1524
1757
|
|
|
1525
1758
|
What it does:
|
|
1526
1759
|
|
|
1527
1760
|
- **The library.** `geminiApi()` with an API key for the endpoint, and `createLargeFiles` with a
|
|
1528
|
-
`FileDocumentStore` in `.data/large-files
|
|
1529
|
-
the pages of a PDF ([PDFs](./pdfs.md))
|
|
1761
|
+
`FileDocumentStore` in `.data/large-files`, `keepOriginals: ["pdf"]`, so the model can look at
|
|
1762
|
+
the pages of a PDF ([PDFs](./pdfs.md)), `createIsolatedExtractors()`, so that PDF and Office files
|
|
1763
|
+
are read in child processes with a memory limit, and `requireOwner: true`, so that no document is
|
|
1764
|
+
ever anyone's. To try Vertex AI, swap the endpoint for `vertexAi()`
|
|
1530
1765
|
([Gemini and Vertex AI](./vertex-and-gemini.md)).
|
|
1766
|
+
- **An owner per browser.** The page sets a cookie, `demo-owner`, of 32 random hex digits, with
|
|
1767
|
+
`HttpOnly` (no script reads it) and `SameSite=Strict` (no other site's page sends it).
|
|
1768
|
+
`getOwner` and the chat route take the owner from it. A request without it is answered `401`
|
|
1769
|
+
"Sign in first.". So two browsers cannot read, delete or ask about each other's files. It is no
|
|
1770
|
+
sign-in: whoever has the cookie is that owner. Put your own sign-in in its place.
|
|
1531
1771
|
- **Uploads.** `createDocumentHandlers` on `node:http`: `POST /api/documents` to `upload`,
|
|
1532
|
-
`
|
|
1533
|
-
anonymous.
|
|
1772
|
+
`GET /api/documents/:id` to `get`, `DELETE /api/documents/:id` to `remove`.
|
|
1534
1773
|
- **The chat route.** `POST /api/chat` takes `{ chatId, question, documentIds }` as JSON, checked
|
|
1535
1774
|
before the stream starts (`400` or `413` otherwise). The server keeps each chat's turns, tool
|
|
1536
|
-
rounds included, in a `Map`
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1775
|
+
rounds included, in a `Map` keyed by owner and chat, so that nobody reads another's chat by its
|
|
1776
|
+
ID (for the demo only: in memory, the latest questions of the latest chats). The route calls
|
|
1777
|
+
`askStream` with the owner, the model, and the explorer when `GEMINI_EXPLORER_MODEL` names one,
|
|
1778
|
+
and passes the stream itself to `writeSseEvents`, so that the question stops as soon as the page
|
|
1779
|
+
goes away. Its `map` puts `run.error` in the app's own words, by `error.name` and
|
|
1540
1780
|
`error.kind`. After the stream, it keeps `result.toolTurns` and the answer when there is one, or
|
|
1541
1781
|
the `toolTurns` of `partialResultOf(error)`.
|
|
1542
1782
|
- **The page.** A file input uploads with `fetch` (`application/octet-stream`, `X-File-Name`,
|
|
@@ -1549,12 +1789,16 @@ What it does:
|
|
|
1549
1789
|
|
|
1550
1790
|
During the work on 0.7.0, the event stream was checked live against the Gemini API: the counts the
|
|
1551
1791
|
events give, the roles of the requests of an explorer pair (`explorer` and `answer`), and this
|
|
1552
|
-
server's stream to the page, end to end.
|
|
1792
|
+
server's stream to the page, end to end. Since 0.9.0, a test of the repository starts it with a
|
|
1793
|
+
scripted model: it listens on `127.0.0.1`, and two browsers cannot read each other's uploads or
|
|
1794
|
+
chats.
|
|
1553
1795
|
|
|
1554
1796
|
It is a demo, kept short. Before you build on it, check your server against this list, which this
|
|
1555
1797
|
guide covers:
|
|
1556
1798
|
|
|
1557
|
-
- `getOwner` returns the signed-in user, and the chat route passes
|
|
1799
|
+
- `getOwner` returns the signed-in user, not a cookie anyone can copy, and the chat route passes
|
|
1800
|
+
the same `owner`. With chats, `getScope` returns the chat, and the chat route passes the same
|
|
1801
|
+
`scope`.
|
|
1558
1802
|
- The JSON body is read and checked before the stream starts, and a bad one gets a `400`.
|
|
1559
1803
|
- The page shows its own message when `answered` in `run.finish` is false.
|
|
1560
1804
|
- `toolTurns` are kept on the server with each question, from `stream.result` or
|
|
@@ -1569,9 +1813,10 @@ guide covers:
|
|
|
1569
1813
|
|
|
1570
1814
|
## Reference
|
|
1571
1815
|
|
|
1572
|
-
- [`llm-large-files/node`](../reference/node.md): `createDocumentHandlers`, `DocumentHandlerOptions
|
|
1573
|
-
`DocumentHandlers`, every route, status and body, the
|
|
1574
|
-
`sseMessageOf`, `SseMessage` and
|
|
1816
|
+
- [`llm-large-files/node`](../reference/node.md): `createDocumentHandlers`, `DocumentHandlerOptions`
|
|
1817
|
+
(`getScope`, `onUploaded`, `onRemoved`), `DocumentHandlers`, every route, status and body, the
|
|
1818
|
+
upload's events, `uploadAnswerOf`, and `writeSseEvents`, `sseMessageOf`, `SseMessage` and
|
|
1819
|
+
`SseWriteOptions`.
|
|
1575
1820
|
- [The library](../reference/library.md): `IngestInput` (`onEvent`, `runId`), `toDocumentSummary`,
|
|
1576
1821
|
`DocumentSummary`, `DocumentMeta`, `ProgressEvent`, `ToolOptions`.
|
|
1577
1822
|
- [Events](../reference/events.md): `AskEvent`, `IngestEvent`, `EventError`, `EventResult`,
|