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