llm-large-files 0.4.1 → 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 +1400 -338
- package/README.md +217 -49
- 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 +117 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +542 -0
- package/dist/anthropic/adapter.js.map +1 -0
- package/dist/anthropic/index.d.ts +3 -0
- package/dist/anthropic/index.d.ts.map +1 -0
- package/dist/anthropic/index.js +2 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/ask.d.ts +200 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +1402 -0
- package/dist/ask.js.map +1 -0
- package/dist/budget.d.ts +23 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +64 -0
- package/dist/budget.js.map +1 -0
- 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 +42 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +138 -0
- package/dist/evidence.js.map +1 -0
- 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 +59 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +226 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +53 -77
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +42 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +16 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +46 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +18 -21
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +49 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +6 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +4 -3
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -2
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -38
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +136 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +401 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +96 -8
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +414 -96
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +37 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +255 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +278 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +222 -0
- package/dist/model.js.map +1 -0
- 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 +109 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +567 -0
- package/dist/openai/adapter.js.map +1 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +2 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/output-limit.d.ts +42 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +121 -0
- package/dist/output-limit.js.map +1 -0
- 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 +76 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +141 -0
- package/dist/retry.js.map +1 -0
- 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 +36 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +153 -0
- package/dist/sse.js.map +1 -0
- 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 +72 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +341 -60
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +128 -4
- 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 +58 -184
- package/docs/configuration.md +34 -490
- package/docs/getting-started.md +412 -177
- 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 +1022 -138
- 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 +902 -90
- package/docs/troubleshooting.md +1390 -0
- package/package.json +22 -4
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +611 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +1560 -0
- package/src/budget.ts +71 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +165 -0
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +271 -0
- package/src/gemini/chat.ts +87 -355
- package/src/gemini/errors.ts +48 -0
- package/src/gemini/generate.ts +67 -94
- package/src/gemini/index.ts +6 -4
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +434 -0
- package/src/index.ts +55 -4
- package/src/library.ts +497 -97
- package/src/map-reduce.ts +266 -59
- package/src/model.ts +433 -0
- 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 +613 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +135 -0
- 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 +176 -0
- package/src/search.ts +63 -10
- package/src/sse.ts +159 -0
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +338 -62
- package/src/types.ts +129 -5
- package/src/zip-directory.ts +136 -0
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
# `llm-large-files/node`
|
|
2
|
+
|
|
3
|
+
This page lists every export of `llm-large-files/node`: `createDocumentHandlers`, its options, and
|
|
4
|
+
the three HTTP handlers it returns, with the request each one expects and every status and body it
|
|
5
|
+
can answer; and `writeSseEvents` and `sseMessageOf`, which send the events of a question or an
|
|
6
|
+
ingest to a browser as Server-Sent Events. It is for you if your server runs on Node and you want
|
|
7
|
+
uploads, look-ups and deletes of documents without writing the routes yourself, or a streamed
|
|
8
|
+
answer without writing the stream yourself. How to mount them, what the browser sends, and how to
|
|
9
|
+
read the stream in the browser are in the guide [web app](../guides/web-app.md).
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { createDocumentHandlers, sseMessageOf, writeSseEvents } from "llm-large-files/node";
|
|
13
|
+
import type { DocumentHandlerOptions, DocumentHandlers, SseMessage, SseWriteOptions } from "llm-large-files/node";
|
|
14
|
+
// What the signatures below use:
|
|
15
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
16
|
+
import type { LargeFiles } from "llm-large-files";
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Contents
|
|
20
|
+
|
|
21
|
+
- [`createDocumentHandlers()`](#createdocumenthandlersfiles-options)
|
|
22
|
+
- [`DocumentHandlerOptions`](#documenthandleroptions)
|
|
23
|
+
- [`DocumentHandlers`](#documenthandlers): [`upload()`](#uploadrequest-response) and
|
|
24
|
+
[its progress as events](#upload-with-progress-accept-textevent-stream),
|
|
25
|
+
[`get()`](#getrequest-response-id), [`remove()`](#removerequest-response-id)
|
|
26
|
+
- [How errors are answered](#how-errors-are-answered)
|
|
27
|
+
- [Server-Sent Events](#server-sent-events): [`writeSseEvents()`](#writesseeventsresponse-events-options),
|
|
28
|
+
[`sseMessageOf()`](#ssemessageofevent), [`SseMessage`](#ssemessage),
|
|
29
|
+
[`SseWriteOptions`](#ssewriteoptions)
|
|
30
|
+
|
|
31
|
+
### createDocumentHandlers(files, options?)
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
declare function createDocumentHandlers(files: LargeFiles, options?: DocumentHandlerOptions): DocumentHandlers;
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Upload, look-up and delete handlers for any Node HTTP server: `node:http` and Express; Fastify
|
|
38
|
+
through `request.raw` and `reply.raw`, with a pass-through parser for `application/octet-stream`
|
|
39
|
+
and `reply.hijack()`; Next.js API routes on the Node runtime, with `bodyParser: false`. The last two
|
|
40
|
+
are not tested in this repository: see [web app](../guides/web-app.md#mount-them-in-plain-nodehttp).
|
|
41
|
+
Each takes Node's `IncomingMessage` and `ServerResponse`, answers with JSON itself, errors
|
|
42
|
+
included, and never rejects, so it can be called without a `catch`.
|
|
43
|
+
|
|
44
|
+
| Parameter | Type | Default | What it does |
|
|
45
|
+
|---|---|---|---|
|
|
46
|
+
| `files` | [`LargeFiles`](./library.md#largefiles) | required | The library that uploads are ingested into and documents are looked up in. Its `maxUploadBytes` ([`LargeFilesOptions`](./library.md#largefilesoptions), 100 MB by default) is the upload limit. |
|
|
47
|
+
| `options` | [`DocumentHandlerOptions`](#documenthandleroptions) | `{}` | Who owns a request. |
|
|
48
|
+
|
|
49
|
+
**Returns** the three [`DocumentHandlers`](#documenthandlers). It makes no request, reads no
|
|
50
|
+
store and throws nothing.
|
|
51
|
+
|
|
52
|
+
The handlers do not check the method or the path of a request: route each request to the one you
|
|
53
|
+
mean. Every response they write has the header `Content-Type: application/json; charset=utf-8`
|
|
54
|
+
and a JSON body, except an upload that asks for its progress as events
|
|
55
|
+
([below](#upload-with-progress-accept-textevent-stream)). When the response has already started
|
|
56
|
+
(`response.headersSent`), they write nothing.
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { createServer } from "node:http";
|
|
60
|
+
import { createLargeFiles, MemoryDocumentStore } from "llm-large-files";
|
|
61
|
+
import { createDocumentHandlers } from "llm-large-files/node";
|
|
62
|
+
|
|
63
|
+
const files = createLargeFiles({ store: new MemoryDocumentStore() });
|
|
64
|
+
|
|
65
|
+
const documents = createDocumentHandlers(files, {
|
|
66
|
+
getOwner: async (request) => {
|
|
67
|
+
const userId = await signedInUser(request); // your sign-in: the user's ID, or undefined
|
|
68
|
+
if (!userId) throw Object.assign(new Error("Sign in to attach files."), { status: 401 });
|
|
69
|
+
return userId;
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
createServer((request, response) => {
|
|
74
|
+
const { pathname } = new URL(request.url ?? "/", "http://localhost");
|
|
75
|
+
const id = /^\/api\/documents\/([^/]+)$/.exec(pathname)?.[1];
|
|
76
|
+
if (pathname === "/api/documents" && request.method === "POST") return void documents.upload(request, response);
|
|
77
|
+
if (id !== undefined && request.method === "GET") return void documents.get(request, response, id);
|
|
78
|
+
if (id !== undefined && request.method === "DELETE") return void documents.remove(request, response, id);
|
|
79
|
+
response.writeHead(404).end();
|
|
80
|
+
}).listen(3000);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Guide: [web app](../guides/web-app.md), with the Express routes, the browser's `fetch`, and an
|
|
84
|
+
upload route of your own for multipart forms or the Fetch API's `Request`.
|
|
85
|
+
|
|
86
|
+
### `DocumentHandlerOptions`
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
type DocumentHandlerOptions = {
|
|
90
|
+
getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
|
|
91
|
+
};
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The options of [`createDocumentHandlers()`](#createdocumenthandlersfiles-options).
|
|
95
|
+
|
|
96
|
+
| Option | Type | Default | What it does |
|
|
97
|
+
|---|---|---|---|
|
|
98
|
+
| `getOwner` | `(request: IncomingMessage) => string \| undefined \| Promise<string \| undefined>` | none: every request is anonymous | The owner of this request, usually the signed-in user's ID. Called at most once per request. In `upload` it runs after the name is read and before the body: an upload without a name is answered `400` without calling it, and a refused upload is never buffered. An empty owner (`""`, or spaces only) is the server's mistake: the upload is answered `500` `{ "error": "Upload failed (empty owner)." }`, before its body is read. So is an owner from JavaScript that is neither a string nor a finite number (`req.user` in place of `req.user.id`, say): `{ "error": "Upload failed (owner is not a string)." }`. |
|
|
99
|
+
|
|
100
|
+
What `getOwner` returns decides what each handler does:
|
|
101
|
+
|
|
102
|
+
| `getOwner` | `upload` | `get` and `remove` |
|
|
103
|
+
|---|---|---|
|
|
104
|
+
| Returns a string that is not empty or only spaces | The document is ingested with that `owner`. | They pass `{ owner }`: they find the documents of that owner, and those that have no owner. A document of another owner answers as one that does not exist. |
|
|
105
|
+
| Returns `undefined`, or there is no `getOwner` | The document has no owner: anyone who has its ID can read it, delete it and ask about it. | They pass no owner: they find only documents that have no owner. |
|
|
106
|
+
| Returns `""`, spaces only, or `null` from JavaScript | Answered `500` `{ "error": "Upload failed (empty owner)." }`, before the body is read, and nothing is logged. Such an owner would be one owner shared by every caller without a user: `user?.id ?? ""` gives it for a user who is not signed in. New in 0.6.0: 0.5.0 stored the document with that owner. | As before: they pass it as `owner`, so documents that 0.5.0 stored with the owner `""` stay readable until they expire. |
|
|
107
|
+
| Returns, from JavaScript, something that is neither a string nor a finite number: an object such as `req.user`, `true`, `NaN`, an array | Answered `500` `{ "error": "Upload failed (owner is not a string)." }`, before the body is read, and nothing is logged. New in 0.6.0. A finite number is taken as the owner, as before. | They pass it as `owner`, as before. |
|
|
108
|
+
| Throws an `Error` whose `status` (or `statusCode`) is a whole number from 400 to 599, as the `http-errors` package makes them | Answered with that status and `{ "error": <the error's message> }`. | The same. |
|
|
109
|
+
| Throws anything else | Answered `500` without the error's message, which may name your hosts: `{ "error": "Upload failed." }` (with the code of a Node system error: "Upload failed (ECONNREFUSED)."). | `500`: "The file could not be looked up." or "The file could not be deleted.", the same way. |
|
|
110
|
+
|
|
111
|
+
The owner is one opaque string, compared as it is. Pass the same string as `owner` to
|
|
112
|
+
`askWithFiles` or `askGemini`, and to `files.getMeta`, `files.getOriginal` and `files.delete`. An
|
|
113
|
+
owner per chat session (`${userId}/${sessionId}`) works the same way:
|
|
114
|
+
[storage](../guides/storage.md). What ownership protects and what it does not:
|
|
115
|
+
[security](../security.md).
|
|
116
|
+
|
|
117
|
+
### `DocumentHandlers`
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
type DocumentHandlers = {
|
|
121
|
+
upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
122
|
+
get(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
123
|
+
remove(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
124
|
+
};
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
What [`createDocumentHandlers()`](#createdocumenthandlersfiles-options) returns. Each handler's
|
|
128
|
+
promise resolves once the response is written; none rejects.
|
|
129
|
+
|
|
130
|
+
| Handler | Route it for | What it does |
|
|
131
|
+
|---|---|---|
|
|
132
|
+
| [`upload(request, response)`](#uploadrequest-response) | `POST`, such as `/api/documents` | Reads the raw body and ingests it as a document of the request's owner. `201` with its summary, or, with `Accept: text/event-stream`, `200` and the ingest's events ending with the summary. |
|
|
133
|
+
| [`get(request, response, id)`](#getrequest-response-id) | `GET`, such as `/api/documents/:id` | `200` with the document's summary, or `404`. |
|
|
134
|
+
| [`remove(request, response, id)`](#removerequest-response-id) | `DELETE`, such as `/api/documents/:id` | Deletes the document. `200` with `{ "deleted": true }` or `{ "deleted": false }`. |
|
|
135
|
+
|
|
136
|
+
The summary is a [`DocumentSummary`](./library.md#documentsummary), the fields of a document that
|
|
137
|
+
are safe to send to a browser: `id`, `name`, `mimeType`, `format`, `bytes`, `lines`,
|
|
138
|
+
`estimatedTokens`, `pages` (for a PDF or a PPTX), `encoding` and `replacedCharacters` (for a text
|
|
139
|
+
file that was not valid UTF-8, since 0.6.0) and `expiresAt`. It holds no `owner`.
|
|
140
|
+
|
|
141
|
+
#### upload(request, response)
|
|
142
|
+
|
|
143
|
+
The request:
|
|
144
|
+
|
|
145
|
+
| Part | What it must be |
|
|
146
|
+
|---|---|
|
|
147
|
+
| Method and path | Any: the handler does not check them. Route `POST` to it. |
|
|
148
|
+
| Body | The file itself, as raw bytes. Not a multipart form: the handler does not parse one. |
|
|
149
|
+
| `X-File-Name` header | The file name, URI-encoded with `encodeURIComponent` so that any name survives a header. It is decoded with `decodeURIComponent` (a value that does not decode is used as it is) and trimmed. |
|
|
150
|
+
| `?name=` query parameter | The file name, when there is no `X-File-Name`. One of the two is required. |
|
|
151
|
+
| `X-File-Type` header | Optional: the MIME type, URI-decoded. |
|
|
152
|
+
| `Content-Type` header | The MIME type when there is no `X-File-Type`, unless it starts with `application/octet-stream`. The value is kept whole, parameters included: a `fetch` with a string body sends `text/plain;charset=UTF-8`, and that is the document's `mimeType`. A type with parameters does not set the format, so name the file with its extension. With neither header, the document's `mimeType` is `application/octet-stream`. Send `application/octet-stream`, which JSON and form parsers leave alone. |
|
|
153
|
+
| `Content-Length` header | Optional. When it is larger than `maxUploadBytes`, the handler answers `413` before it reads anything. |
|
|
154
|
+
| `Accept` header | Optional. When it names `text/event-stream`, the ingest is answered with its progress as Server-Sent Events: see [upload with progress](#upload-with-progress-accept-textevent-stream). New in 0.7.0. |
|
|
155
|
+
|
|
156
|
+
`files.ingest` then keeps the last path segment of the name, without control characters and
|
|
157
|
+
characters that show nothing, up to 255 characters and never cut in the middle of a character, and takes the format
|
|
158
|
+
from the name's extension first, then from the MIME type
|
|
159
|
+
([`detectFormat`](./library.md#detectformatname-mimetype)).
|
|
160
|
+
|
|
161
|
+
What it does, in order:
|
|
162
|
+
|
|
163
|
+
1. Reads the name. Without one, it answers `400`.
|
|
164
|
+
2. Calls `getOwner`, and checks what it returned: `""`, spaces only or `null`, or from JavaScript
|
|
165
|
+
a value that is neither a string nor a finite number, is answered `500` (see
|
|
166
|
+
[`DocumentHandlerOptions`](#documenthandleroptions)).
|
|
167
|
+
3. Reads the body, up to `files.maxUploadBytes`:
|
|
168
|
+
- a `Uint8Array` or `Buffer` that a framework left in `request.body` (`express.raw()`) is used
|
|
169
|
+
as the file, with the same limit;
|
|
170
|
+
- an object with fields in `request.body` (`express.json()` on a JSON request) is answered
|
|
171
|
+
`400`;
|
|
172
|
+
- otherwise it reads the request stream. Past the limit it stops reading, and answers `413`.
|
|
173
|
+
The rest of the body is not read: a client that sent no `Content-Length` (a chunked upload)
|
|
174
|
+
and then sends its next request on the same keep-alive connection, as a `node:http` agent
|
|
175
|
+
does, gets no answer to that request. `fetch`, and a client that sends `Content-Length`, are
|
|
176
|
+
not affected. A stream that another middleware has already read gives no bytes, and the
|
|
177
|
+
upload is answered `422` as an empty file.
|
|
178
|
+
4. Ingests it: `files.ingest({ name, bytes, mimeType, owner, signal })`, `mimeType` and `owner`
|
|
179
|
+
only when there are any. The `signal` aborts when the client closes the connection before the
|
|
180
|
+
answer is sent: the ingest stops between two pages or pieces, and nothing is stored. The
|
|
181
|
+
answer then goes to no one.
|
|
182
|
+
5. Answers `201` with the document's summary. With `Accept: text/event-stream`, steps 4 and 5 are
|
|
183
|
+
a stream of events instead ([below](#upload-with-progress-accept-textevent-stream)).
|
|
184
|
+
|
|
185
|
+
The responses:
|
|
186
|
+
|
|
187
|
+
| Status | Body | When |
|
|
188
|
+
|---|---|---|
|
|
189
|
+
| `201` | The [`DocumentSummary`](./library.md#documentsummary) of the new document | It was ingested. |
|
|
190
|
+
| `400` | `{ "error": "Name the file with an X-File-Name header or a ?name= query parameter." }` | No name. |
|
|
191
|
+
| `400` | `{ "error": "The upload body was already parsed by another middleware. Mount the upload route before body parsers, or send Content-Type: application/octet-stream." }` | `request.body` is an object with fields. |
|
|
192
|
+
| `413` | `{ "error": "The file is larger than the 100 MB upload limit." }`, with your `maxUploadBytes` in its place (`512 KB`, `1000 B`) | `Content-Length`, the bytes read, or the `Buffer` in `request.body` are over `maxUploadBytes`. |
|
|
193
|
+
| `422` | `{ "error": <the message of files.ingest> }` | The file cannot be read. The message says why and is meant for the user: "app.log is empty.", "app.log did not contain any text.", "This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.", "This file is gzip-compressed. Decompress it, then attach the text file inside.", "This file is a ZIP archive. Extract it, then attach the text file you need.", a PDF with no text layer, and a PDF, DOCX or PPTX while the optional dependency that reads it is missing ("Reading PDF files needs the optional dependency "unpdf".") or, for a PDF, cannot run on this Node ("The unpdf installed cannot read PDF files on Node 20 (…). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.", see [defaultExtractors](./library.md#defaultextractors)). A text file is never refused for its encoding. A file past the limits of `createLargeFiles`: more text than `maxTextBytes`, more pages than `maxPdfPages`, longer to read than `ingestTimeoutMs` ("report.pdf took too long to read (more than 2 min). Split it, or save it as plain text, and attach that."), or built to exhaust the server ([every message](../guides/pdfs.md#what-is-refused)). An extractor of your own that throws an `Error` gives its message here too. |
|
|
194
|
+
| 400 to 599 | `{ "error": <the error's message> }` | `getOwner`, an extractor or the store threw an error with that `status` or `statusCode`. |
|
|
195
|
+
| `500` | `{ "error": "Upload failed (empty owner)." }` | `getOwner` returned `""`, spaces only or `null`. The body is not read. New in 0.6.0. |
|
|
196
|
+
| `500` | `{ "error": "Upload failed (owner is not a string)." }` | `getOwner` returned, from JavaScript, something that is neither a string nor a finite number: an object such as `req.user`, `true`, `NaN`, an array. The body is not read. New in 0.6.0. |
|
|
197
|
+
| `500` | `{ "error": "Upload failed (ENOSPC)." }` | The store failed with a Node system error, one with a `code` and a `syscall`. Only the code is passed on. |
|
|
198
|
+
| `500` | `{ "error": "Upload failed." }` | `getOwner` threw an error without a status, or the request body could not be read: the client went away, or a proxy cut the upload. Node's error for a client that went away has a `code` (`ECONNRESET`) but no `syscall`, so no code is added. An error of either kind that has a `code` and a `syscall` is answered as in the row above, with its code. |
|
|
199
|
+
| `500` | `{ "error": "Upload failed." }` | The store failed while it wrote the document, with an error that has no `status` or `statusCode` from 400 to 599 and is not a Node system error (a database driver's error, say). Or `files.ingest` threw a value that is not an `Error` (an extractor of your own that throws a string, say). Such a value with a `code` and a `syscall` gets its code, as in the `ENOSPC` row. The error's own message is not sent. See below. |
|
|
200
|
+
|
|
201
|
+
A store that fails while it writes is answered `500` "Upload failed." when its error has neither a
|
|
202
|
+
`status` (or `statusCode`) from 400 to 599 nor a Node system error's `code` and `syscall`. Its
|
|
203
|
+
message may name a host, so it is not sent, and the handlers log nothing. `files.ingest` throws
|
|
204
|
+
that error unchanged, and the handler knows it by a mark that `ingest` keeps. The package does not
|
|
205
|
+
export the mark, so two paths answer such an error `422` with the store's message, as a file that
|
|
206
|
+
cannot be read:
|
|
207
|
+
|
|
208
|
+
- an `ingest` of your own that throws a new error in place of the store's, such as `ingestInProcess`
|
|
209
|
+
in [deployment](../guides/deployment.md#uploads-and-ingest);
|
|
210
|
+
- a route of your own around `files.ingest`, such as the one in
|
|
211
|
+
[web app](../guides/web-app.md#filesingest-and-its-errors) with its `ingestFailure` helper.
|
|
212
|
+
|
|
213
|
+
In a store of your own, log the failure and throw an error with a `status` (a `503`, say) and a
|
|
214
|
+
message without hosts: every path keeps that status. An `ingest` of your own must copy the
|
|
215
|
+
`status`, and a system error's `code` and `syscall`, onto the error it throws.
|
|
216
|
+
[Storage](../guides/storage.md) has the rules for a store's errors.
|
|
217
|
+
|
|
218
|
+
#### Upload with progress: `Accept: text/event-stream`
|
|
219
|
+
|
|
220
|
+
New in 0.7.0. An upload whose `Accept` header names `text/event-stream` is answered with the
|
|
221
|
+
ingest's events as Server-Sent Events, so that the page can show how far the server has read the
|
|
222
|
+
file: the pages of a PDF, the parts of a DOCX, the writes to the store. Without that header,
|
|
223
|
+
nothing changes: `201` and JSON, as above.
|
|
224
|
+
|
|
225
|
+
The handler reads the `Accept` header this way:
|
|
226
|
+
|
|
227
|
+
- The header is split at commas into media ranges. One of them must be `text/event-stream`
|
|
228
|
+
itself, in any case, with spaces allowed around it and its parameters
|
|
229
|
+
(`TEXT/Event-Stream ; q=0.5` counts).
|
|
230
|
+
- Its `q`, when there is one, must be a number above 0. `q=0` and `q=0.0` keep the JSON answer, and
|
|
231
|
+
so does a `q` that is not a number.
|
|
232
|
+
- A wildcard keeps the JSON answer: `*/*` and `text/*` do not ask for events. So does any other
|
|
233
|
+
type, such as `application/json`.
|
|
234
|
+
- Other parameters, such as `charset=utf-8`, change nothing.
|
|
235
|
+
|
|
236
|
+
What stays JSON: every check that runs before the ingest answers as it always did, with its status
|
|
237
|
+
and `{ "error": "…" }`, because the stream has not started yet. That is a missing name (`400`), a
|
|
238
|
+
refusal or a bad owner from `getOwner` (its status, or `500`), a body another middleware parsed
|
|
239
|
+
(`400`), and a file over `maxUploadBytes` (`413`). Only a file that passes them is answered `200`
|
|
240
|
+
with the event-stream headers of [`writeSseEvents()`](#writesseeventsresponse-events-options) and
|
|
241
|
+
a `: keep-alive` comment every 15 seconds.
|
|
242
|
+
|
|
243
|
+
Each message is `id: <seq>`, `event: <type>` and `data: <the event as JSON>`. The events are those
|
|
244
|
+
of [`IngestEvent`](./events.md#ingestevent), stamped with `seq` (1, 2, 3… with no gaps), `runId`
|
|
245
|
+
("ing_" and 16 hex digits) and `time` (milliseconds since 1970):
|
|
246
|
+
|
|
247
|
+
| Event | `data` besides `type`, `seq`, `runId` and `time` | When |
|
|
248
|
+
|---|---|---|
|
|
249
|
+
| `ingest.start` | `name` (cleaned), `format` (what the name and the type say: a text file can still become a log), `bytes` | First. |
|
|
250
|
+
| `ingest.progress` | `stage` (`"decode"`, `"extract"`, `"check"`, `"pictures"`, `"prepare"`, `"index"` or `"store"`), `done`, `total` (absent when not known), `unit` (`"pages"`, `"parts"`, `"bytes"` or `"characters"`) | At most about every 12 ms for a stage, and once more when the stage ends. A stage with nothing to report may send none ([stages and units](./events.md#stages-and-units)). |
|
|
251
|
+
| `ingest.finish` | `document`: the [`DocumentSummary`](./library.md#documentsummary), the same fields as the body of a `201` | Last, when the document is stored. |
|
|
252
|
+
| `ingest.error` | `error`: `{ "message": …, "status": … }`, the message and status the JSON answer would have | Last, when the ingest fails. |
|
|
253
|
+
|
|
254
|
+
```text
|
|
255
|
+
id: 4
|
|
256
|
+
event: ingest.finish
|
|
257
|
+
data: {"type":"ingest.finish","document":{"id":"doc_f6502d2f94694d709c7db2ec634c8397","name":"b.log","mimeType":"text/plain","format":"log","bytes":81000,"lines":3000,"estimatedTokens":74940,"expiresAt":"2026-11-25T19:09:01.650Z"},"seq":4,"runId":"ing_d19490eacdcd4546","time":1795374541651}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
- **The stream always ends with one `ingest.finish` or one `ingest.error`.** A file the ingest
|
|
261
|
+
refuses at once (an empty file) still gets `ingest.start`, then `ingest.error`. When an `ingest`
|
|
262
|
+
of your own sends no events at all, the handler adds the last one: then that one event is the
|
|
263
|
+
whole stream, with `seq` 1.
|
|
264
|
+
- **`ingest.error` holds what the JSON answer would.** A file that cannot be read gives
|
|
265
|
+
`{ "message": "This file looks binary, not text. …", "status": 422 }`. A store that failed is
|
|
266
|
+
`{ "message": "Upload failed.", "status": 500 }`, never the store's own message, which may name a
|
|
267
|
+
host. An error with a status keeps it. The error has no `kind` or `name` here, unlike the
|
|
268
|
+
`EventError` of `files.ingest`'s own events.
|
|
269
|
+
- **The status is `200` whatever happens next.** Once the stream has started, a failure can only be
|
|
270
|
+
an `ingest.error` event.
|
|
271
|
+
- **A client that goes away stops the ingest**, as in step 4: nothing is stored, and nothing more
|
|
272
|
+
is written.
|
|
273
|
+
- **The handler still never rejects.**
|
|
274
|
+
|
|
275
|
+
How to read the stream in the browser: [web app](../guides/web-app.md#upload-with-progress).
|
|
276
|
+
|
|
277
|
+
#### get(request, response, id)
|
|
278
|
+
|
|
279
|
+
The request: route `GET` to it; the handler does not check the method. `id` is the document ID,
|
|
280
|
+
taken from your route. Nothing else is read but what `getOwner` reads.
|
|
281
|
+
|
|
282
|
+
| Status | Body | When |
|
|
283
|
+
|---|---|---|
|
|
284
|
+
| `200` | The [`DocumentSummary`](./library.md#documentsummary) | The document is there, has not expired, and has no owner or the owner `getOwner` returned. |
|
|
285
|
+
| `404` | `{ "error": "This file is no longer available." }` | `id` is not a document ID, was never uploaded, has expired or been deleted, or belongs to another owner. |
|
|
286
|
+
| 400 to 599 | `{ "error": <the error's message> }` | `getOwner` threw an error with that `status` or `statusCode`. |
|
|
287
|
+
| `500` | `{ "error": "The file could not be looked up (EIO)." }` | The store could not be read ([`DocumentStoreError`](./library.md#documentstoreerror)), with the code of the system error behind it, when there is one. |
|
|
288
|
+
| `500` | `{ "error": "The file could not be looked up." }` | The store could not be read and gave no system error code, or `getOwner` threw an error without a status. |
|
|
289
|
+
|
|
290
|
+
#### remove(request, response, id)
|
|
291
|
+
|
|
292
|
+
The request: route `DELETE` to it; the handler does not check the method. `id` is the document
|
|
293
|
+
ID, taken from your route. It deletes the document through `files.delete`, which removes it from
|
|
294
|
+
the store: its text, its index and any kept original, as far as your store's `delete` does.
|
|
295
|
+
|
|
296
|
+
| Status | Body | When |
|
|
297
|
+
|---|---|---|
|
|
298
|
+
| `200` | `{ "deleted": true }` | The document was deleted. |
|
|
299
|
+
| `200` | `{ "deleted": false }` | This owner has no such document: `id` is not a document ID, was never uploaded, has expired or been deleted, or belongs to another owner. Also when the store's `delete` returned `false`. It never answers `404`. |
|
|
300
|
+
| 400 to 599 | `{ "error": <the error's message> }` | `getOwner`, or the store's `delete`, threw an error with that `status` or `statusCode`. |
|
|
301
|
+
| `500` | `{ "error": "The file could not be deleted (EIO)." }` | The store could not be read, or its `delete` failed with a Node system error, with that error's code. |
|
|
302
|
+
| `500` | `{ "error": "The file could not be deleted." }` | The same with no system error code, or `getOwner` threw an error without a status. |
|
|
303
|
+
|
|
304
|
+
## How errors are answered
|
|
305
|
+
|
|
306
|
+
The three handlers answer an error by one rule:
|
|
307
|
+
|
|
308
|
+
- **An error with a status.** An `Error` whose `status`, or else `statusCode`, is a whole number
|
|
309
|
+
from 400 to 599 is answered with that status and `{ "error": <its message> }`. With an empty
|
|
310
|
+
message, the body says what failed instead ("Upload failed.", "The file could not be looked
|
|
311
|
+
up.", "The file could not be deleted."). A `413` is always answered with the size message of
|
|
312
|
+
`upload`.
|
|
313
|
+
- **Any other error** is the server's trouble: `500`, with what failed and, for a Node system error
|
|
314
|
+
(one with a `code` and a `syscall`), its code: "Upload failed (ENOSPC).". The error's own message
|
|
315
|
+
is never sent, since it can name paths and hosts of your server.
|
|
316
|
+
- **The one exception** is in `upload`: an `Error` from `files.ingest` that has neither a status nor
|
|
317
|
+
a system error's `code` and `syscall` is a file that cannot be read, `422` with its message,
|
|
318
|
+
unless `files.ingest` marked it as an error the store threw while it wrote the document. That
|
|
319
|
+
one, and a thrown value that is not an `Error`, are answered as any other error. An `ingest` of
|
|
320
|
+
your own that throws a new error in its place loses the mark ([upload](#uploadrequest-response)).
|
|
321
|
+
|
|
322
|
+
Guide: [errors and reliability](../guides/errors-and-reliability.md), for the errors of a question
|
|
323
|
+
itself; [web app](../guides/web-app.md), for what to show in the browser.
|
|
324
|
+
|
|
325
|
+
## Server-Sent Events
|
|
326
|
+
|
|
327
|
+
New in 0.7.0. Two functions send the events of a question (`askStream`, or
|
|
328
|
+
[`eventStream`](./events.md#eventstreamrun-options) over `askGemini`) or of an ingest to a browser,
|
|
329
|
+
one Server-Sent Events message per event. The events themselves are in the
|
|
330
|
+
[events reference](./events.md). The guide [web app](../guides/web-app.md#the-event-stream) has a
|
|
331
|
+
whole route and the browser code that reads it.
|
|
332
|
+
|
|
333
|
+
### writeSseEvents(response, events, options?)
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
declare function writeSseEvents<E extends { type: string; seq: number }>(
|
|
337
|
+
response: ServerResponse,
|
|
338
|
+
events: AsyncIterable<E>,
|
|
339
|
+
options?: SseWriteOptions<E>,
|
|
340
|
+
): Promise<void>;
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
Sends `events` on `response` as Server-Sent Events, and ends the response after the last one. Any
|
|
344
|
+
iterable of objects with a `type` and a `seq` works: an `askStream`, an `eventStream`, or an async
|
|
345
|
+
generator of your own.
|
|
346
|
+
|
|
347
|
+
| Parameter | Type | Default | What it does |
|
|
348
|
+
|---|---|---|---|
|
|
349
|
+
| `response` | `ServerResponse` | required | The response to write on. Express's `res` is one. |
|
|
350
|
+
| `events` | `AsyncIterable<E>` | required | The events. Pass an `askStream` or an `eventStream` itself, not a generator around it: see [when the client goes away](#when-the-client-goes-away). |
|
|
351
|
+
| `options` | [`SseWriteOptions<E>`](#ssewriteoptions) | `{}` | The keep-alive, extra headers, what to send for each event, and whether to end the response. |
|
|
352
|
+
|
|
353
|
+
**What it writes.** When no headers are sent yet, it sets these and writes a `200` at once
|
|
354
|
+
(`flushHeaders()`), so the browser's `fetch` resolves before the first event:
|
|
355
|
+
|
|
356
|
+
| Header | Value |
|
|
357
|
+
|---|---|
|
|
358
|
+
| `Content-Type` | `text/event-stream; charset=utf-8` |
|
|
359
|
+
| `Cache-Control` | `no-cache, no-transform` |
|
|
360
|
+
| `Connection` | `keep-alive` |
|
|
361
|
+
| `X-Accel-Buffering` | `no` |
|
|
362
|
+
|
|
363
|
+
Then `headers` from the options are set on top: a name replaces the header above whatever its case
|
|
364
|
+
(`cache-control` replaces `Cache-Control`). A header you set on the response before the call
|
|
365
|
+
(`res.setHeader`, a CORS middleware) is kept, unless it has one of these names. The status is
|
|
366
|
+
always `200`. When the headers are already sent (you called `writeHead` yourself), it writes none
|
|
367
|
+
and leaves yours as they are.
|
|
368
|
+
|
|
369
|
+
Each event then becomes one message:
|
|
370
|
+
|
|
371
|
+
```text
|
|
372
|
+
id: 7
|
|
373
|
+
event: tool.start
|
|
374
|
+
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}
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
- `id` is the message's `id`, or else the event's `seq`.
|
|
378
|
+
- `event` is the message's `event`, or else the event's `type`.
|
|
379
|
+
- `data` is the message's `data` as JSON, always on one line. U+2028 and U+2029, which JSON leaves as
|
|
380
|
+
they are, are written `\u2028` and `\u2029`: the same JSON, which a client that splits the stream
|
|
381
|
+
on every Unicode line break still reads whole. `undefined` is sent as `null`.
|
|
382
|
+
- A line break in an `id` or an `event` becomes a space, so that it cannot end the field early.
|
|
383
|
+
|
|
384
|
+
What is sent for an event comes from `map`, [`sseMessageOf()`](#ssemessageofevent) by default. A
|
|
385
|
+
`: keep-alive` comment goes out every `heartbeatMs` (15 seconds by default) while the stream is
|
|
386
|
+
open; browsers and readers skip comments, and proxies see traffic. None is written while it waits
|
|
387
|
+
for the client.
|
|
388
|
+
|
|
389
|
+
**When the client reads slowly.** When `response.write()` returns false, it waits for `drain`
|
|
390
|
+
before it takes the next event. The question or the ingest does not wait: its events wait in
|
|
391
|
+
memory, in the `eventStream`, until they are read.
|
|
392
|
+
|
|
393
|
+
**When it resolves, and when it rejects.**
|
|
394
|
+
|
|
395
|
+
| What happens | What it does |
|
|
396
|
+
|---|---|
|
|
397
|
+
| The events end | Ends the response (unless `end: false`) and resolves. |
|
|
398
|
+
| The client goes away, or someone else ends the response | Stops reading, calls the iterator's `return()` and resolves. Nothing more is written. |
|
|
399
|
+
| The response is already ended or destroyed when it is called | Writes nothing, calls `return()` and resolves. |
|
|
400
|
+
| `map` throws | Calls `return()`, ends the response (unless `end: false`), and rejects with that error. |
|
|
401
|
+
| The iterable throws | Ends the response (unless `end: false`) and rejects with that error. It does not call `return()` of an iterator that failed. An `askStream` or an `eventStream` never throws: a run that fails ends with its `run.error` or `ingest.error` event, and the promise resolves. |
|
|
402
|
+
| A header cannot be set (an invalid name or value in `headers`) | Calls `return()`, destroys the response without a status line, and rejects with that error. |
|
|
403
|
+
|
|
404
|
+
#### When the client goes away
|
|
405
|
+
|
|
406
|
+
When the response closes before the end (the user pressed Stop, closed the tab or lost the
|
|
407
|
+
connection) or `finish`es because something else ended it, `writeSseEvents` stops reading at once,
|
|
408
|
+
even while it waits for the next event, and calls `return()` on the iterator it was reading:
|
|
409
|
+
|
|
410
|
+
- **An `askStream` or an `eventStream` passed in directly** stops its run at once: its signal
|
|
411
|
+
aborts with an `AbortError` ("The events stopped being read."), the request under way stops, and
|
|
412
|
+
no tool call starts. The stream's `result` rejects with that error, and
|
|
413
|
+
[`partialResultOf(error)`](./ask.md#partialresultoferror) gives what the question found. The
|
|
414
|
+
`run.error` event is not sent: nobody reads.
|
|
415
|
+
- **An async generator that wraps one** (to rename events or skip some) is only stopped when it
|
|
416
|
+
next yields. A question that waits on a long model request goes on, and costs, until then. To
|
|
417
|
+
change what is sent, use `map` and pass the stream itself; return `undefined` from `map` to skip
|
|
418
|
+
an event. If you wrap it anyway, stop the run yourself:
|
|
419
|
+
|
|
420
|
+
```ts
|
|
421
|
+
import type { ServerResponse } from "node:http";
|
|
422
|
+
import { askStream, type AskEvent, type AskOptions } from "llm-large-files";
|
|
423
|
+
import { writeSseEvents } from "llm-large-files/node";
|
|
424
|
+
|
|
425
|
+
export async function sendWithoutRequests(res: ServerResponse, options: AskOptions): Promise<void> {
|
|
426
|
+
const stream = askStream(options);
|
|
427
|
+
// The generator only notices the client left when it next yields: stop the question yourself.
|
|
428
|
+
res.once("close", () => stream.abort());
|
|
429
|
+
async function* withoutRequests(): AsyncGenerator<AskEvent> {
|
|
430
|
+
for await (const event of stream) if (!event.type.startsWith("request.")) yield event;
|
|
431
|
+
}
|
|
432
|
+
await writeSseEvents(res, withoutRequests());
|
|
433
|
+
}
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
The same with `map`, which needs no listener of its own:
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
import type { ServerResponse } from "node:http";
|
|
440
|
+
import { askStream, type AskOptions } from "llm-large-files";
|
|
441
|
+
import { sseMessageOf, writeSseEvents } from "llm-large-files/node";
|
|
442
|
+
|
|
443
|
+
export async function sendWithoutRequests(res: ServerResponse, options: AskOptions): Promise<void> {
|
|
444
|
+
await writeSseEvents(res, askStream(options), {
|
|
445
|
+
map: (event) => (event.type.startsWith("request.") ? undefined : sseMessageOf(event)),
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
### sseMessageOf(event)
|
|
451
|
+
|
|
452
|
+
```ts
|
|
453
|
+
declare function sseMessageOf<E extends { type: string; seq: number }>(event: E): SseMessage;
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
The default `map` of [`writeSseEvents()`](#writesseeventsresponse-events-options): what is sent for
|
|
457
|
+
an event. Call it from a `map` of your own to change one event and send the others as they are.
|
|
458
|
+
|
|
459
|
+
It returns `{ event: <type>, id: <seq>, data }`. The `data` is the event itself, `type`, `seq`,
|
|
460
|
+
`runId` and `time` included, for every event but two, which it sends smaller:
|
|
461
|
+
|
|
462
|
+
| Event | `data` |
|
|
463
|
+
|---|---|
|
|
464
|
+
| `run.finish` | `{ type, seq, runId, time, result }`, where `result` holds only `answered`, `text`, `finishReason`, `blockReason`, `steps`, `evidence`, `turns` and `usage`. Not `toolTurns`, `plan`, `budget` or `lastUsage`. |
|
|
465
|
+
| `run.error` | `{ type, seq, runId, time, error, partial }`, where `error` is the event's [`EventError`](./events.md#errors-eventerror) and `partial` holds only `steps`, `evidence` and `usage` of the partial result. Without a partial result, `partial` is left out of the JSON. |
|
|
466
|
+
| Any other event, ingest events included | The event as it is. |
|
|
467
|
+
|
|
468
|
+
A field that is `undefined`, such as `finishReason` or `blockReason`, is left out of the JSON.
|
|
469
|
+
|
|
470
|
+
`toolTurns` are left out even when the question ran with `eventResults: true`: keep them on the
|
|
471
|
+
server, from the stream's `result` or from `partialResultOf(error)`
|
|
472
|
+
([conversations](../guides/conversations.md)). `eventResults: true` does put each tool result in
|
|
473
|
+
its `tool.end` event (`result`), and `sseMessageOf` sends that event as it is: leave
|
|
474
|
+
`eventResults` off for a stream to a browser, or drop `result` in a `map` of your own.
|
|
475
|
+
|
|
476
|
+
```ts
|
|
477
|
+
import type { AskEvent } from "llm-large-files";
|
|
478
|
+
import { sseMessageOf, type SseMessage } from "llm-large-files/node";
|
|
479
|
+
|
|
480
|
+
/** run.error in the app's own words; every other event as sseMessageOf sends it. */
|
|
481
|
+
export function mapForPage(event: AskEvent): SseMessage {
|
|
482
|
+
if (event.type !== "run.error") return sseMessageOf(event);
|
|
483
|
+
const message = event.error.kind === "rate_limit" ? "The assistant is busy. Try again in a minute." : event.error.message;
|
|
484
|
+
return sseMessageOf({ ...event, error: { ...event.error, message } });
|
|
485
|
+
}
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
### `SseMessage`
|
|
489
|
+
|
|
490
|
+
```ts
|
|
491
|
+
type SseMessage = {
|
|
492
|
+
event?: string;
|
|
493
|
+
data: unknown;
|
|
494
|
+
id?: string | number;
|
|
495
|
+
};
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
One message, as a `map` returns it.
|
|
499
|
+
|
|
500
|
+
| Field | Type | Default | What it does |
|
|
501
|
+
|---|---|---|---|
|
|
502
|
+
| `event` | `string` | the event's `type` | The `event:` field: the name a browser's `EventSource` dispatches on. |
|
|
503
|
+
| `data` | `unknown` | required | Any JSON value, sent as JSON on one `data:` line. |
|
|
504
|
+
| `id` | `string \| number` | the event's `seq` | The `id:` field. |
|
|
505
|
+
|
|
506
|
+
### `SseWriteOptions`
|
|
507
|
+
|
|
508
|
+
```ts
|
|
509
|
+
type SseWriteOptions<E> = {
|
|
510
|
+
heartbeatMs?: number;
|
|
511
|
+
headers?: Record<string, string | number | string[]>;
|
|
512
|
+
map?: (event: E) => SseMessage | undefined;
|
|
513
|
+
end?: boolean;
|
|
514
|
+
};
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
The options of [`writeSseEvents()`](#writesseeventsresponse-events-options).
|
|
518
|
+
|
|
519
|
+
| Option | Type | Default | What it does |
|
|
520
|
+
|---|---|---|---|
|
|
521
|
+
| `heartbeatMs` | `number` | `15000` | Milliseconds between two `: keep-alive` comments, which keep proxies and load balancers from closing a quiet stream. 0 sends none. The timer does not keep the process alive. |
|
|
522
|
+
| `headers` | `Record<string, string \| number \| string[]>` | none | Headers to send besides the event-stream ones, or in their place: a name replaces one of them whatever its case. Used only when no headers are sent yet. |
|
|
523
|
+
| `map` | `(event: E) => SseMessage \| undefined` | [`sseMessageOf`](#ssemessageofevent) | What to send for an event. Return `undefined` to skip it. A throw stops the run and rejects. |
|
|
524
|
+
| `end` | `boolean` | `true` | False keeps the response open after the last event, for something you write after it, or to end it yourself once the question is saved. You must then end it: `if (!res.writableEnded && !res.destroyed) res.end()`. |
|
|
525
|
+
|
|
526
|
+
Guide: [web app](../guides/web-app.md), with the route, the browser code that reads the events,
|
|
527
|
+
keep-alive comments and proxies; [deployment](../guides/deployment.md#streamed-answers-behind-proxies),
|
|
528
|
+
for timeouts and buffering on the way to the browser.
|