llm-large-files 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1402 -467
- package/README.md +188 -60
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +190 -39
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +60 -4
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1068 -206
- package/dist/ask.js.map +1 -1
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +3 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +108 -61
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +13 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +405 -85
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +182 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +311 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +269 -42
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +102 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1012 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +897 -103
- package/docs/troubleshooting.md +1390 -0
- package/package.json +2 -2
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +196 -39
- package/src/ask.ts +1087 -202
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +5 -2
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +118 -65
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +23 -10
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/http.ts +376 -1
- package/src/index.ts +27 -5
- package/src/library.ts +459 -85
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +236 -3
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +306 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +49 -5
- package/src/search.ts +63 -10
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +261 -42
- package/src/types.ts +107 -4
- package/src/zip-directory.ts +136 -0
package/src/http.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Small things every adapter needs for its HTTP requests.
|
|
2
|
+
import { sliceWhole } from "./text.js";
|
|
2
3
|
|
|
3
4
|
/** Request headers, or a function returning them: called for each request, so a token can be renewed. */
|
|
4
5
|
export type HeaderSource = Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
|
|
@@ -30,6 +31,380 @@ export function unreachableReason(error: unknown): string {
|
|
|
30
31
|
return error instanceof Error && error.message ? ` (${error.message})` : "";
|
|
31
32
|
}
|
|
32
33
|
|
|
34
|
+
/**
|
|
35
|
+
* The longest wait, by default, between two pieces of a reply once it has started to arrive: an
|
|
36
|
+
* event of a stream, a keep-alive, a piece of a body. A model that is writing sends something
|
|
37
|
+
* well within it.
|
|
38
|
+
*/
|
|
39
|
+
export const DEFAULT_IDLE_TIMEOUT_MS = 300_000;
|
|
40
|
+
/**
|
|
41
|
+
* The longest wait, by default, for the first piece of a reply. Headers do not count: some servers
|
|
42
|
+
* send them at once. A model that thinks sends nothing while it does (Gemini without its thoughts,
|
|
43
|
+
* OpenAI's reasoning models), and a reply that is not streamed comes whole at the end, so this
|
|
44
|
+
* wait is long enough for a model that thinks long on a large request.
|
|
45
|
+
*/
|
|
46
|
+
export const DEFAULT_FIRST_BYTE_TIMEOUT_MS = 600_000;
|
|
47
|
+
|
|
48
|
+
/** The longest delay `setTimeout` takes: a longer one fires at once. About 24.8 days, which is no limit. */
|
|
49
|
+
const LONGEST_TIMER_MS = 2_147_483_647;
|
|
50
|
+
|
|
51
|
+
/** Watches a request for silence: see `idleWatch`. */
|
|
52
|
+
export type IdleWatch = {
|
|
53
|
+
/** The signal for `fetch`: it aborts when the caller's does, or when nothing arrived for the whole wait. */
|
|
54
|
+
readonly signal: AbortSignal | undefined;
|
|
55
|
+
/** A piece of the reply arrived: from now on the wait is the one between pieces, and it starts again. */
|
|
56
|
+
pulse(): void;
|
|
57
|
+
/** The reply is in, or failed: the watch ends. */
|
|
58
|
+
stop(): void;
|
|
59
|
+
/** True once a wait ran out with nothing arriving. The request was then aborted by the watch, not by the caller. */
|
|
60
|
+
readonly expired: boolean;
|
|
61
|
+
/** The wait that ran out, in milliseconds, for the message. */
|
|
62
|
+
readonly waitedMs: number;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** How long an adapter waits: before the first piece of a reply, and between pieces. 0 waits without end. */
|
|
66
|
+
export type IdleWaits = { firstByteTimeoutMs?: number | undefined; idleTimeoutMs?: number | undefined };
|
|
67
|
+
|
|
68
|
+
const watching = (ms: number | undefined): ms is number => ms !== undefined && Number.isFinite(ms) && ms > 0;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A watch on one model request: when nothing arrives for the wait (`firstByteTimeoutMs` before the
|
|
72
|
+
* first piece of the reply, `idleTimeoutMs` between pieces), the request is aborted, and `expired`
|
|
73
|
+
* tells that apart from the caller's own abort. There is no cap on the time of a reply that keeps
|
|
74
|
+
* arriving. A wait of 0 watches nothing.
|
|
75
|
+
*/
|
|
76
|
+
export function idleWatch(caller: AbortSignal | undefined, waits: IdleWaits = {}): IdleWatch {
|
|
77
|
+
const first = waits.firstByteTimeoutMs ?? DEFAULT_FIRST_BYTE_TIMEOUT_MS;
|
|
78
|
+
const between = waits.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
|
|
79
|
+
if (!watching(first) && !watching(between)) {
|
|
80
|
+
return { signal: caller, pulse() {}, stop() {}, expired: false, waitedMs: 0 };
|
|
81
|
+
}
|
|
82
|
+
const controller = new AbortController();
|
|
83
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
84
|
+
let expired = false;
|
|
85
|
+
let stopped = false;
|
|
86
|
+
let waitedMs = 0;
|
|
87
|
+
const arm = (ms: number) => {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
timer = undefined;
|
|
90
|
+
if (stopped || !watching(ms)) return;
|
|
91
|
+
timer = setTimeout(() => {
|
|
92
|
+
expired = true;
|
|
93
|
+
waitedMs = ms;
|
|
94
|
+
controller.abort(new Error(`Nothing arrived from the model for ${Math.round(ms / 1_000)} s.`));
|
|
95
|
+
}, Math.min(ms, LONGEST_TIMER_MS));
|
|
96
|
+
};
|
|
97
|
+
arm(first);
|
|
98
|
+
return {
|
|
99
|
+
signal: caller ? AbortSignal.any([caller, controller.signal]) : controller.signal,
|
|
100
|
+
pulse: () => arm(between),
|
|
101
|
+
stop() {
|
|
102
|
+
stopped = true;
|
|
103
|
+
clearTimeout(timer);
|
|
104
|
+
},
|
|
105
|
+
get expired() {
|
|
106
|
+
return expired;
|
|
107
|
+
},
|
|
108
|
+
get waitedMs() {
|
|
109
|
+
return waitedMs;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* How long, in milliseconds, the end of a streamed body is waited for once the reply said it is
|
|
116
|
+
* whole (OpenAI's `[DONE]`, Claude's `message_stop`). A server ends the body at once: the wait lets
|
|
117
|
+
* the connection be used again. One that leaves it open is not waited for longer.
|
|
118
|
+
*/
|
|
119
|
+
export const REPLY_END_GRACE_MS = 1_000;
|
|
120
|
+
|
|
121
|
+
/** The end of a streamed reply, once it said it is whole: see `replyEnd`. */
|
|
122
|
+
export type ReplyEnd = {
|
|
123
|
+
/** The signal to read the stream with: the watch's, and the end of the grace that follows `reached`. */
|
|
124
|
+
readonly signal: AbortSignal;
|
|
125
|
+
/** The reply said it is whole: the watch ends, and the body is read for `REPLY_END_GRACE_MS` more at most. */
|
|
126
|
+
reached(): void;
|
|
127
|
+
/**
|
|
128
|
+
* True once the reply said it is whole (`reached`): a connection that breaks after that, rather
|
|
129
|
+
* than end, loses nothing of the reply.
|
|
130
|
+
*/
|
|
131
|
+
readonly whole: boolean;
|
|
132
|
+
/** True for the error of a body left after that grace: what came before it is the whole reply. */
|
|
133
|
+
left(error: unknown): boolean;
|
|
134
|
+
/** The reading is over: the grace is not waited for. */
|
|
135
|
+
dispose(): void;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The end of a streamed reply. A server that says the reply is whole and then leaves the
|
|
140
|
+
* connection open would hold the request until the watch ran out, and fail it as silent, with the
|
|
141
|
+
* whole answer already shown.
|
|
142
|
+
*/
|
|
143
|
+
export function replyEnd(watch: Pick<IdleWatch, "signal" | "stop">): ReplyEnd {
|
|
144
|
+
const controller = new AbortController();
|
|
145
|
+
const ended = new Error("The reply is whole, and its body was left open.");
|
|
146
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
147
|
+
return {
|
|
148
|
+
signal: watch.signal ? AbortSignal.any([watch.signal, controller.signal]) : controller.signal,
|
|
149
|
+
reached() {
|
|
150
|
+
if (timer !== undefined) return;
|
|
151
|
+
watch.stop();
|
|
152
|
+
timer = setTimeout(() => controller.abort(ended), REPLY_END_GRACE_MS);
|
|
153
|
+
},
|
|
154
|
+
get whole() {
|
|
155
|
+
return timer !== undefined;
|
|
156
|
+
},
|
|
157
|
+
left: (error) => error === ended,
|
|
158
|
+
dispose() {
|
|
159
|
+
clearTimeout(timer);
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* A wait for `next` that ends with the signal's reason when the signal aborts first. The global
|
|
166
|
+
* `fetch` ends the body of a request whose signal aborts; another `fetch` (or a test's) may not,
|
|
167
|
+
* and a watch on the request must still end it. The tool loop waits for a model request the same
|
|
168
|
+
* way: an adapter of an application's own may not stop when the signal aborts, and one written in
|
|
169
|
+
* plain JavaScript may give back a value, or a thenable, rather than a promise.
|
|
170
|
+
*/
|
|
171
|
+
export function until<T>(next: T | PromiseLike<T>, signal: AbortSignal | undefined): Promise<T> {
|
|
172
|
+
const promise = Promise.resolve(next);
|
|
173
|
+
if (!signal) return promise;
|
|
174
|
+
if (signal.aborted) {
|
|
175
|
+
// The read is not waited for: when it fails later, that is no error of anyone's.
|
|
176
|
+
promise.catch(() => undefined);
|
|
177
|
+
return Promise.reject(signal.reason);
|
|
178
|
+
}
|
|
179
|
+
return new Promise<T>((resolve, reject) => {
|
|
180
|
+
const stop = () => reject(signal.reason);
|
|
181
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
182
|
+
promise.then(
|
|
183
|
+
(value) => {
|
|
184
|
+
signal.removeEventListener("abort", stop);
|
|
185
|
+
resolve(value);
|
|
186
|
+
},
|
|
187
|
+
(error: unknown) => {
|
|
188
|
+
signal.removeEventListener("abort", stop);
|
|
189
|
+
reject(error);
|
|
190
|
+
},
|
|
191
|
+
);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The pieces of a body as they arrive: from a web stream (the global `fetch`), or from a Node
|
|
197
|
+
* stream (node-fetch and the like), which has no `getReader`. A reader that is left early is
|
|
198
|
+
* cancelled. When `signal` aborts, the next piece is not waited for.
|
|
199
|
+
*/
|
|
200
|
+
export async function* bodyPieces(body: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array | string>, signal?: AbortSignal): AsyncGenerator<Uint8Array> {
|
|
201
|
+
if (typeof (body as ReadableStream<Uint8Array>).getReader === "function") {
|
|
202
|
+
const reader = (body as ReadableStream<Uint8Array>).getReader();
|
|
203
|
+
try {
|
|
204
|
+
for (;;) {
|
|
205
|
+
// No read is started after an abort.
|
|
206
|
+
signal?.throwIfAborted();
|
|
207
|
+
const { done, value } = await until(reader.read(), signal);
|
|
208
|
+
if (done) return;
|
|
209
|
+
if (value) yield value;
|
|
210
|
+
}
|
|
211
|
+
} finally {
|
|
212
|
+
// Not waited for: a stream whose cancel never settles (a `fetch` of a test, or of a library)
|
|
213
|
+
// would hold the request after its watch ran out, or after the reply was whole.
|
|
214
|
+
try {
|
|
215
|
+
Promise.resolve(reader.cancel()).catch(() => undefined);
|
|
216
|
+
reader.releaseLock();
|
|
217
|
+
} catch {
|
|
218
|
+
// A reader of the app's whose `cancel()` gives no promise, or throws at once, is no error of the caller's.
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const encoder = new TextEncoder();
|
|
223
|
+
const pieces = (body as AsyncIterable<Uint8Array | string>)[Symbol.asyncIterator]();
|
|
224
|
+
try {
|
|
225
|
+
for (;;) {
|
|
226
|
+
signal?.throwIfAborted();
|
|
227
|
+
const { done, value } = await until(pieces.next(), signal);
|
|
228
|
+
if (done) return;
|
|
229
|
+
yield typeof value === "string" ? encoder.encode(value) : value;
|
|
230
|
+
}
|
|
231
|
+
} finally {
|
|
232
|
+
// A read may still be waiting, on a stream that the fetch does not end when the signal
|
|
233
|
+
// aborts: `return()` would wait behind it for ever. The stream is destroyed (without the
|
|
234
|
+
// reason, which an HTTP request would raise as an error of its own).
|
|
235
|
+
if (signal?.aborted) (body as { destroy?: () => void }).destroy?.();
|
|
236
|
+
// Not waited for, as a web stream's cancel is not: an iterable of the app's whose `return()`
|
|
237
|
+
// never settles would hold the caller, and the error it is to be told of.
|
|
238
|
+
try {
|
|
239
|
+
Promise.resolve(pieces.return?.()).catch(() => undefined);
|
|
240
|
+
} catch {
|
|
241
|
+
// A `return()` that throws at once is no error of the caller's.
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Reads a body as text a piece at a time, calling `onData` for each piece. */
|
|
247
|
+
async function readText(body: ReadableStream<Uint8Array>, onData: () => void, signal: AbortSignal | undefined): Promise<string> {
|
|
248
|
+
const decoder = new TextDecoder();
|
|
249
|
+
let text = "";
|
|
250
|
+
for await (const piece of bodyPieces(body, signal)) {
|
|
251
|
+
if (piece.length === 0) continue;
|
|
252
|
+
text += decoder.decode(piece, { stream: true });
|
|
253
|
+
onData();
|
|
254
|
+
}
|
|
255
|
+
return text + decoder.decode();
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The body of a response that is not streamed, as JSON. A connection that fails while the body
|
|
260
|
+
* arrives is `unreachable(error)`, a request that got no answer, which is sent again like one that
|
|
261
|
+
* failed before the headers; it is noted as a reply cut off on its way (`isCutReply`), and so is a
|
|
262
|
+
* body that ended empty. A body that came whole but is not JSON (a gateway's HTML page) is
|
|
263
|
+
* `notJson(error)`: see `notJsonMessage`.
|
|
264
|
+
* With an `IdleWatch`, pass its `pulse` as `onData` (keep-alive blank lines count) and its signal.
|
|
265
|
+
*/
|
|
266
|
+
export async function readJson<T>(response: Response, stopped: () => boolean, unreachable: (error: unknown) => Error, watch: Pick<IdleWatch, "pulse" | "signal"> | undefined, notJson: (error: unknown) => Error): Promise<T> {
|
|
267
|
+
let text: string;
|
|
268
|
+
try {
|
|
269
|
+
text = watch && response.body ? await readText(response.body, watch.pulse, watch.signal) : await response.text();
|
|
270
|
+
} catch (error) {
|
|
271
|
+
if (stopped()) throw error;
|
|
272
|
+
throw noteCutReply(unreachable(error));
|
|
273
|
+
}
|
|
274
|
+
// A body that ended before anything came is a reply cut off on its way, not a page in its place.
|
|
275
|
+
if (!text.trim()) throw noteCutReply(unreachable(new Error("the reply was empty")));
|
|
276
|
+
try {
|
|
277
|
+
return JSON.parse(text) as T;
|
|
278
|
+
} catch (error) {
|
|
279
|
+
throw notJson(error);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* The message of a reply that came with a status of success but is not JSON: most often a page of
|
|
285
|
+
* a proxy or a gateway (a sign-in page, an error page) that answered in the model's place. It is
|
|
286
|
+
* not sent again: the same page would most likely come back. `who` is "Gemini's", "Claude's"…
|
|
287
|
+
*/
|
|
288
|
+
export function notJsonMessage(who: string, response: Response): string {
|
|
289
|
+
const type = (response.headers.get("content-type") ?? "").split(";")[0]!.trim();
|
|
290
|
+
return `${who} reply could not be read: it was not JSON${type ? ` (${type})` : ""}. A proxy or gateway may have answered in its place.`;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Errors of a reply that was cut off on its way: it began to arrive, and did not arrive whole. */
|
|
294
|
+
const cutReplies = new WeakSet<object>();
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Takes note that this error is that of a reply cut off on its way (a stream that closed before
|
|
298
|
+
* its end, a connection that failed while the reply arrived), not of a model that could not be
|
|
299
|
+
* reached at all. Returns the error.
|
|
300
|
+
*/
|
|
301
|
+
export function noteCutReply<E extends Error>(error: E): E {
|
|
302
|
+
cutReplies.add(error);
|
|
303
|
+
return error;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Whether this is the error of a reply cut off on its way (see `noteCutReply`). */
|
|
307
|
+
export function isCutReply(error: unknown): boolean {
|
|
308
|
+
return typeof error === "object" && error !== null && cutReplies.has(error);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* The most white space, in characters, that the body of a reply asked for as a stream is read
|
|
313
|
+
* through to tell what it is (see `streamedReply`). A body with more before anything else is read
|
|
314
|
+
* as JSON.
|
|
315
|
+
*/
|
|
316
|
+
const LONGEST_BLANK_START = 65_536;
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* The first pieces of a body told to be events, without the byte order mark and the white space
|
|
320
|
+
* before the first event: an event stream's parser reads a first line " data: {...}" as a field
|
|
321
|
+
* named " data", and drops the event.
|
|
322
|
+
*/
|
|
323
|
+
function withoutBlankStart(pieces: Uint8Array[]): Uint8Array[] {
|
|
324
|
+
const total = pieces.reduce((sum, piece) => sum + piece.length, 0);
|
|
325
|
+
const bytes = new Uint8Array(total);
|
|
326
|
+
let at = 0;
|
|
327
|
+
for (const piece of pieces) {
|
|
328
|
+
bytes.set(piece, at);
|
|
329
|
+
at += piece.length;
|
|
330
|
+
}
|
|
331
|
+
let skip = bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf ? 3 : 0;
|
|
332
|
+
while (skip < total && (bytes[skip] === 0x20 || bytes[skip] === 0x09 || bytes[skip] === 0x0a || bytes[skip] === 0x0d)) skip++;
|
|
333
|
+
return skip === 0 ? pieces : [bytes.subarray(skip)];
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* How to read the body of a reply that was asked for as a stream: as server-sent events, or as
|
|
338
|
+
* JSON in one piece. A reply of type `text/event-stream` is events. Of any other type, its first
|
|
339
|
+
* characters tell: a gateway may stream under another type (`application/octet-stream`, or none),
|
|
340
|
+
* and a server may answer in one piece. A body that starts like neither (an HTML page), or with
|
|
341
|
+
* more than `LONGEST_BLANK_START` characters of white space, is read as JSON, which it is not: see
|
|
342
|
+
* `readJson`. The pieces read to tell are pulses of the watch, and the `response` returned holds
|
|
343
|
+
* the whole body again.
|
|
344
|
+
*/
|
|
345
|
+
export async function streamedReply(response: Response, watch: Pick<IdleWatch, "pulse" | "signal">): Promise<{ events: boolean; response: Response }> {
|
|
346
|
+
const type = response.headers.get("content-type") ?? "";
|
|
347
|
+
if (/event-stream/i.test(type)) return { events: true, response };
|
|
348
|
+
if (!response.body) return { events: false, response };
|
|
349
|
+
// The body given back may be left before its end (a reply that said it is whole, and stayed
|
|
350
|
+
// open): its reader then stops this one too, which cancels the body it reads.
|
|
351
|
+
const left = new AbortController();
|
|
352
|
+
const pieces = bodyPieces(response.body, watch.signal ? AbortSignal.any([watch.signal, left.signal]) : left.signal);
|
|
353
|
+
const head: Uint8Array[] = [];
|
|
354
|
+
const decoder = new TextDecoder();
|
|
355
|
+
/** The start of the body, without the white space before it: only that is looked at. */
|
|
356
|
+
let start = "";
|
|
357
|
+
/** The characters of white space that came before it. */
|
|
358
|
+
let blank = 0;
|
|
359
|
+
let ended = false;
|
|
360
|
+
let events: boolean | undefined;
|
|
361
|
+
while (events === undefined) {
|
|
362
|
+
const next = await pieces.next();
|
|
363
|
+
if (next.done) {
|
|
364
|
+
ended = true;
|
|
365
|
+
events = startsEvents(start, true) ?? false;
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
if (next.value.length > 0) watch.pulse();
|
|
369
|
+
head.push(next.value);
|
|
370
|
+
const text = start + decoder.decode(next.value, { stream: true });
|
|
371
|
+
start = text.trimStart();
|
|
372
|
+
blank += text.length - start.length;
|
|
373
|
+
// A body of white space alone is not waited on to its end: past so much of it, the body is read
|
|
374
|
+
// as JSON, which it is not, whatever comes after it, and however the pieces are cut.
|
|
375
|
+
events = blank > LONGEST_BLANK_START ? false : startsEvents(start, false);
|
|
376
|
+
}
|
|
377
|
+
const body = new ReadableStream<Uint8Array>({
|
|
378
|
+
start(controller) {
|
|
379
|
+
for (const piece of events ? withoutBlankStart(head) : head) controller.enqueue(piece);
|
|
380
|
+
if (ended) controller.close();
|
|
381
|
+
},
|
|
382
|
+
async pull(controller) {
|
|
383
|
+
const next = await pieces.next();
|
|
384
|
+
if (next.done) controller.close();
|
|
385
|
+
else controller.enqueue(next.value);
|
|
386
|
+
},
|
|
387
|
+
cancel(reason) {
|
|
388
|
+
// A read may still wait on the body, and `return` would wait behind it: the read is stopped.
|
|
389
|
+
left.abort(reason);
|
|
390
|
+
void pieces.return(undefined).catch(() => undefined);
|
|
391
|
+
},
|
|
392
|
+
// Nothing is read ahead of the reader: what is left unread when it stops is cancelled.
|
|
393
|
+
}, { highWaterMark: 0 });
|
|
394
|
+
return { events, response: new Response(body, { headers: type ? { "content-type": type } : {} }) };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Whether a body that starts with `text` is server-sent events (a field such as `data:`, or a
|
|
399
|
+
* comment), or else JSON or a page: undefined while too little has come to tell.
|
|
400
|
+
*/
|
|
401
|
+
function startsEvents(text: string, whole: boolean): boolean | undefined {
|
|
402
|
+
const start = text.trimStart();
|
|
403
|
+
if (/^(?::|(?:data|event|id|retry):)/.test(start)) return true;
|
|
404
|
+
if (/^[{[]/.test(start) || start.length >= 6 || /[\r\n]/.test(start)) return false;
|
|
405
|
+
return whole ? false : undefined;
|
|
406
|
+
}
|
|
407
|
+
|
|
33
408
|
/**
|
|
34
409
|
* Arguments of a tool call that arrived as JSON text, and, when the text is not a JSON object,
|
|
35
410
|
* why the call cannot be run: a model that is told so sends the call again.
|
|
@@ -43,7 +418,7 @@ export function readArguments(text: unknown): { args: Record<string, unknown>; p
|
|
|
43
418
|
} catch {
|
|
44
419
|
// Reported below.
|
|
45
420
|
}
|
|
46
|
-
return { args: {}, problem: `The arguments of this call were not a JSON object, and it was not run: ${text
|
|
421
|
+
return { args: {}, problem: `The arguments of this call were not a JSON object, and it was not run: ${sliceWhole(text, 300)}. Send the call again.` };
|
|
47
422
|
}
|
|
48
423
|
|
|
49
424
|
/** Arguments of a tool call that arrived as JSON text. Text that is no JSON object gives none. */
|
package/src/index.ts
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
// Core: provider-neutral. The tool loop is `askWithFiles`, and a model provider is an adapter:
|
|
2
2
|
// "llm-large-files/gemini", "llm-large-files/openai", "llm-large-files/anthropic", or your own.
|
|
3
3
|
// Node HTTP handlers are in "llm-large-files/node".
|
|
4
|
-
export { createLargeFiles, DEFAULT_CACHE_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, NEVER_EXPIRES, toDocumentSummary } from "./library.js";
|
|
4
|
+
export { createLargeFiles, DEFAULT_CACHE_BYTES, DEFAULT_INGEST_TIMEOUT_MS, DEFAULT_MAX_PDF_PAGES, DEFAULT_MAX_TEXT_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, NEVER_EXPIRES, toDocumentSummary } from "./library.js";
|
|
5
5
|
export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, PrepareOptions, ToolOptions } from "./library.js";
|
|
6
6
|
export { DEFAULT_BUDGET, resolveBudget } from "./budget.js";
|
|
7
7
|
export type { ModelLimits } from "./budget.js";
|
|
8
|
-
export { askWithFiles, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS } from "./ask.js";
|
|
8
|
+
export { askStream, askWithFiles, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "./ask.js";
|
|
9
9
|
export type { AskLimits, AskOptions, AskResult } from "./ask.js";
|
|
10
|
-
export { DocumentsNotFoundError, ModelRequestError, UsageMeter } from "./model.js";
|
|
10
|
+
export { classifyModelError, DocumentsNotFoundError, errorKindOf, ModelRequestError, UsageMeter } from "./model.js";
|
|
11
11
|
export type {
|
|
12
12
|
ChatMessage,
|
|
13
|
+
ModelErrorClass,
|
|
14
|
+
ModelErrorKind,
|
|
13
15
|
ChatTurn,
|
|
14
16
|
ModelAdapter,
|
|
15
17
|
ModelCapabilities,
|
|
@@ -26,11 +28,31 @@ export type {
|
|
|
26
28
|
ToolTurn,
|
|
27
29
|
UsageTotals,
|
|
28
30
|
} from "./model.js";
|
|
31
|
+
export { eventStream, newRunId } from "./events.js";
|
|
32
|
+
export type {
|
|
33
|
+
AskEvent,
|
|
34
|
+
DocumentRef,
|
|
35
|
+
EventBase,
|
|
36
|
+
EventError,
|
|
37
|
+
EventResult,
|
|
38
|
+
EventStream,
|
|
39
|
+
IngestEvent,
|
|
40
|
+
IngestStage,
|
|
41
|
+
LibraryEvent,
|
|
42
|
+
NoticeCode,
|
|
43
|
+
NoticeDisplay,
|
|
44
|
+
RequestPurpose,
|
|
45
|
+
RequestRole,
|
|
46
|
+
ToolOutcome,
|
|
47
|
+
} from "./events.js";
|
|
29
48
|
export { evidenceOf, mergeRanges, stubResult } from "./evidence.js";
|
|
30
49
|
export type { Evidence, NumberRange } from "./evidence.js";
|
|
31
50
|
export { isRetryableStatus, retryAfterMs, withRetry } from "./retry.js";
|
|
32
|
-
export type { RetryOptions } from "./retry.js";
|
|
33
|
-
export { parseSseJson } from "./sse.js";
|
|
51
|
+
export type { RetryNotice, RetryOptions } from "./retry.js";
|
|
52
|
+
export { parseSseJson, SseEventTooLongError } from "./sse.js";
|
|
53
|
+
export type { SseHooks } from "./sse.js";
|
|
54
|
+
export { DEFAULT_FIRST_BYTE_TIMEOUT_MS, DEFAULT_IDLE_TIMEOUT_MS } from "./http.js";
|
|
55
|
+
export type { IdleWaits } from "./http.js";
|
|
34
56
|
export { DocumentStoreError } from "./errors.js";
|
|
35
57
|
export { FileDocumentStore, MemoryDocumentStore, DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
36
58
|
export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
|