llm-large-files 0.9.0 → 0.10.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 +446 -0
- package/README.md +13 -7
- package/dist/access.d.ts +45 -3
- package/dist/access.d.ts.map +1 -1
- package/dist/access.js +106 -3
- package/dist/access.js.map +1 -1
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +86 -13
- package/dist/aggregate.js.map +1 -1
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +2 -2
- package/dist/analyze.js.map +1 -1
- package/dist/answer-info.d.ts +26 -0
- package/dist/answer-info.d.ts.map +1 -0
- package/dist/answer-info.js +32 -0
- package/dist/answer-info.js.map +1 -0
- package/dist/anthropic/adapter.d.ts +5 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +35 -10
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +115 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +572 -103
- package/dist/ask.js.map +1 -1
- package/dist/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +291 -0
- package/dist/citations.js.map +1 -0
- package/dist/error-info.d.ts +13 -0
- package/dist/error-info.d.ts.map +1 -1
- package/dist/error-info.js +37 -1
- package/dist/error-info.js.map +1 -1
- package/dist/errors.d.ts +3 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +3 -1
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +25 -7
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +21 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +6 -1
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +35 -4
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +68 -29
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +28 -55
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -27
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +59 -11
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +33 -7
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +39 -5
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +70 -9
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +53 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +100 -50
- 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/http.d.ts +41 -3
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +40 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +9 -1
- package/dist/ingest.d.ts.map +1 -1
- package/dist/ingest.js +50 -25
- package/dist/ingest.js.map +1 -1
- package/dist/library.d.ts +129 -2
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +224 -149
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +176 -10
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +804 -58
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +36 -4
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +17 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +29 -8
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +148 -126
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.js +2 -2
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/spool.d.ts +9 -5
- package/dist/node/spool.d.ts.map +1 -1
- package/dist/node/spool.js +28 -15
- package/dist/node/spool.js.map +1 -1
- package/dist/node/sse.d.ts +6 -5
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +8 -7
- package/dist/node/sse.js.map +1 -1
- package/dist/openai/adapter.d.ts +5 -1
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +53 -12
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +2 -1
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +5 -2
- package/dist/output-limit.js.map +1 -1
- package/dist/pdf-outline.d.ts +71 -0
- package/dist/pdf-outline.d.ts.map +1 -0
- package/dist/pdf-outline.js +414 -0
- package/dist/pdf-outline.js.map +1 -0
- package/dist/plan.d.ts +137 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +248 -26
- package/dist/plan.js.map +1 -1
- package/dist/prepare.d.ts +50 -0
- package/dist/prepare.d.ts.map +1 -0
- package/dist/prepare.js +207 -0
- package/dist/prepare.js.map +1 -0
- package/dist/ranged.d.ts +2 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +16 -3
- package/dist/ranged.js.map +1 -1
- package/dist/search.d.ts +7 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +72 -10
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +6 -0
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +82 -11
- package/dist/stores.js.map +1 -1
- package/dist/tools.d.ts +22 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +323 -76
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +49 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/whole-cost.d.ts +37 -0
- package/dist/whole-cost.d.ts.map +1 -0
- package/dist/whole-cost.js +46 -0
- package/dist/whole-cost.js.map +1 -0
- package/docs/README.md +4 -0
- package/docs/guides/anthropic.md +5 -2
- package/docs/guides/conversations.md +1 -1
- package/docs/guides/costs-and-limits.md +132 -36
- package/docs/guides/deployment.md +106 -13
- package/docs/guides/errors-and-reliability.md +157 -45
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +33 -6
- package/docs/guides/pdfs.md +96 -7
- package/docs/guides/storage.md +46 -3
- package/docs/guides/testing.md +71 -0
- package/docs/guides/vertex-and-gemini.md +159 -50
- package/docs/guides/web-app.md +10 -6
- package/docs/how-it-works.md +120 -22
- package/docs/measurements.md +172 -5
- package/docs/publishing.md +76 -4
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +262 -35
- package/docs/reference/errors-and-retries.md +30 -2
- package/docs/reference/events.md +27 -10
- package/docs/reference/gemini.md +184 -68
- package/docs/reference/library.md +190 -23
- package/docs/reference/node.md +51 -17
- package/docs/reference/openai.md +21 -10
- package/docs/reference/tools.md +271 -26
- package/docs/security.md +101 -12
- package/docs/troubleshooting.md +14 -12
- package/docs/upgrading-0.10.md +472 -0
- package/package.json +5 -1
- package/src/access.ts +127 -4
- package/src/aggregate.ts +92 -14
- package/src/analyze.ts +2 -2
- package/src/answer-info.ts +45 -0
- package/src/anthropic/adapter.ts +40 -11
- package/src/ask.ts +646 -106
- package/src/citations.ts +294 -0
- package/src/error-info.ts +36 -1
- package/src/errors.ts +3 -1
- package/src/events.ts +29 -6
- package/src/evidence.ts +21 -2
- package/src/extract.ts +6 -1
- package/src/gemini/adapter.ts +99 -32
- package/src/gemini/chat.ts +53 -82
- package/src/gemini/endpoints.ts +89 -16
- package/src/gemini/errors.ts +74 -11
- package/src/gemini/generate.ts +147 -57
- package/src/gemini/index.ts +3 -3
- package/src/http.ts +65 -4
- package/src/index.ts +6 -4
- package/src/ingest.ts +58 -27
- package/src/library.ts +336 -142
- package/src/map-reduce.ts +855 -67
- package/src/model.ts +44 -4
- package/src/node/handlers.ts +159 -118
- package/src/node/index.ts +1 -0
- package/src/node/ingest-child.ts +2 -2
- package/src/node/spool.ts +28 -14
- package/src/node/sse.ts +8 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +16 -3
- package/src/search.ts +69 -13
- package/src/stores.ts +76 -11
- package/src/tools.ts +327 -75
- package/src/types.ts +45 -1
- package/src/whole-cost.ts +64 -0
package/src/library.ts
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
callerOf, checkMetaVersion, checkStuck, documentContext, isTimeLimit, mayUse, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, storeTimeout,
|
|
3
|
+
stuckCalls, type AccessRules, type Caller,
|
|
4
|
+
} from "./access.js";
|
|
2
5
|
import { givenBudget, resolveBudget, type ModelLimits } from "./budget.js";
|
|
3
6
|
import { DocumentCache, documentVersion, type Sized } from "./cache.js";
|
|
7
|
+
import type { DocumentStoreOperation } from "./errors.js";
|
|
4
8
|
import type { IngestEvent } from "./events.js";
|
|
9
|
+
import { until } from "./http.js";
|
|
5
10
|
import { ingestDocument, LONGEST_TIMER_MS, type IngestContext } from "./ingest.js";
|
|
6
11
|
import { Limiter } from "./limiter.js";
|
|
7
|
-
import { canBeReadWhole,
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
12
|
+
import { canBeReadWhole, TABLE_FORMATS } from "./plan.js";
|
|
13
|
+
import { prepareDocuments, type PrepareContext } from "./prepare.js";
|
|
14
|
+
import { openRangedDocument, pieceKey, RangedDocument, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
|
|
15
|
+
import { SearchableDocument, type DocumentSource } from "./search.js";
|
|
10
16
|
import { TimeSlicer } from "./pause.js";
|
|
11
17
|
import { checkScope } from "./scope.js";
|
|
12
18
|
import { isSha256, sha256InSlices } from "./source.js";
|
|
@@ -25,6 +31,7 @@ import type {
|
|
|
25
31
|
GenerateText,
|
|
26
32
|
PreparedContext,
|
|
27
33
|
ProgressListener,
|
|
34
|
+
ToolName,
|
|
28
35
|
ToolSet,
|
|
29
36
|
} from "./types.js";
|
|
30
37
|
|
|
@@ -155,6 +162,36 @@ export type LargeFilesOptions = {
|
|
|
155
162
|
* store, not a user's access. Defaults to false. New in 0.9.0.
|
|
156
163
|
*/
|
|
157
164
|
requireScope?: boolean;
|
|
165
|
+
/**
|
|
166
|
+
* The most time one store call may take, in milliseconds: a look-up of a document (`getMeta`), a
|
|
167
|
+
* read of its text (whole, or a range of it), of its index or of its original, and a delete.
|
|
168
|
+
* Past it, the call fails with a `DocumentStoreError` of code "ETIMEDOUT" (status 503): the call
|
|
169
|
+
* itself goes on, as nothing can stop it, and counts as stuck until it ends. A call inside a
|
|
170
|
+
* question's tool call ends the question. Defaults to 30,000; 0 sets no limit, and so does a time
|
|
171
|
+
* past what a timer can wait. Keep it above the time your store takes to read the largest text
|
|
172
|
+
* loaded whole (`wholeDocumentBytes`). `ingest` keeps its own limits (`ingestTimeoutMs`), past
|
|
173
|
+
* which its store calls count as stuck too, and `sweep` has `sweepTimeoutMs`. New in 0.10.0.
|
|
174
|
+
*/
|
|
175
|
+
storeTimeoutMs?: number;
|
|
176
|
+
/**
|
|
177
|
+
* How many calls of this process may be stuck (past their time limit, and not ended) before every
|
|
178
|
+
* new store call of this library, those of `ingest` included, fails at once, without calling the
|
|
179
|
+
* store, with code "STORE_STUCK" (status 503). A store call is stuck past `storeTimeoutMs`, and
|
|
180
|
+
* one of `ingest` past the time it gives its store calls (`ingestTimeoutMs`, 2 minutes when that
|
|
181
|
+
* is 0). The count is the process's, as the threads of libuv are: a store call that does not
|
|
182
|
+
* answer holds one of them, and with all of them held every file call and DNS look-up of the
|
|
183
|
+
* process waits. Defaults to half of `UV_THREADPOOL_SIZE` (4 when it is not set), read when the
|
|
184
|
+
* library is made as libuv reads it (an empty value, 0, or one without leading digits is 1
|
|
185
|
+
* thread), and at least 1: 2 by default, 16 with 32 threads. `Infinity` refuses nothing. New in
|
|
186
|
+
* 0.10.0.
|
|
187
|
+
*/
|
|
188
|
+
maxStuckStoreCalls?: number;
|
|
189
|
+
/**
|
|
190
|
+
* The most time one `sweep` may take, in milliseconds: past it, `sweep` fails with a
|
|
191
|
+
* `DocumentStoreError` of code "ETIMEDOUT", and the sweep goes on. A sweep never counts as a stuck
|
|
192
|
+
* call. Defaults to 0: no limit. New in 0.10.0.
|
|
193
|
+
*/
|
|
194
|
+
sweepTimeoutMs?: number;
|
|
158
195
|
/** Clock override, for tests. */
|
|
159
196
|
now?: () => Date;
|
|
160
197
|
};
|
|
@@ -260,7 +297,17 @@ export type IngestFromSource = Omit<IngestInput, "bytes"> & { source: IngestSour
|
|
|
260
297
|
* Access options. When a document has an owner, only that owner can use it. `scope`, new in 0.9.0:
|
|
261
298
|
* the scope of the caller; a document stored with a scope serves only a caller with the same one.
|
|
262
299
|
*/
|
|
263
|
-
export type AccessOptions = {
|
|
300
|
+
export type AccessOptions = {
|
|
301
|
+
owner?: string;
|
|
302
|
+
scope?: DocumentScope;
|
|
303
|
+
/**
|
|
304
|
+
* Ends this caller's waits for the store, with the signal's reason: never a store call that other
|
|
305
|
+
* callers wait on too (one opening of a document serves every caller of its scope), and never the
|
|
306
|
+
* store call itself, which nothing can stop. Read by `getMeta`, `getOriginal`, `delete`,
|
|
307
|
+
* `prepare`, `toolsFor`, and `tools` with `access`. New in 0.10.0.
|
|
308
|
+
*/
|
|
309
|
+
signal?: AbortSignal;
|
|
310
|
+
};
|
|
264
311
|
|
|
265
312
|
export type PrepareOptions = AccessOptions & {
|
|
266
313
|
/**
|
|
@@ -281,6 +328,20 @@ export type PrepareOptions = AccessOptions & {
|
|
|
281
328
|
* `wholeDocumentAnalysis: false`.
|
|
282
329
|
*/
|
|
283
330
|
wholeDocumentAnalysis?: boolean;
|
|
331
|
+
/**
|
|
332
|
+
* Number the lines of the documents sent whole, as the tools number them ("12| text"), and plan
|
|
333
|
+
* them at that size. Defaults to false here, so that `prepare` gives the blocks of 0.9;
|
|
334
|
+
* `askWithFiles` asks for true unless `AskOptions.numberInline` is false. A value that is not
|
|
335
|
+
* true or false is a TypeError. New in 0.10.0.
|
|
336
|
+
*/
|
|
337
|
+
numberInline?: boolean;
|
|
338
|
+
/**
|
|
339
|
+
* "tools": list the documents sent whole whose tables the tools can count in `toolable`, with
|
|
340
|
+
* their document_id in the first line of their block; "text": as in 0.9. Defaults to "text"
|
|
341
|
+
* here; `askWithFiles` asks for "tools" unless `AskOptions.inlineTables` is "text". Another value
|
|
342
|
+
* is a TypeError. New in 0.10.0.
|
|
343
|
+
*/
|
|
344
|
+
inlineTables?: "tools" | "text";
|
|
284
345
|
};
|
|
285
346
|
|
|
286
347
|
export type ToolOptions = {
|
|
@@ -322,6 +383,19 @@ export type ToolOptions = {
|
|
|
322
383
|
* PDFs that are not searched because their text is already in the prompt.
|
|
323
384
|
*/
|
|
324
385
|
viewPages?: boolean | DocumentMeta[];
|
|
386
|
+
/**
|
|
387
|
+
* Declare exactly these tools, in the order the tool set declares them (search, read, overview,
|
|
388
|
+
* aggregate, analyze, view), in place of those the documents call for. A call of a tool that is
|
|
389
|
+
* not declared is not run, and a declared tool that cannot run (aggregate_table with no table,
|
|
390
|
+
* view_pages with no page to show) answers each call with its reason. `askWithFiles` declares
|
|
391
|
+
* the tools a question over a table sent whole needs. New in 0.10.0.
|
|
392
|
+
*/
|
|
393
|
+
declare?: readonly ToolName[];
|
|
394
|
+
/**
|
|
395
|
+
* The IDs of documents sent whole: `analyze_whole_document` refuses them, as they are shown in
|
|
396
|
+
* full, and `aggregate_table` says how to cite their lines (`cite`). New in 0.10.0.
|
|
397
|
+
*/
|
|
398
|
+
inline?: readonly string[];
|
|
325
399
|
};
|
|
326
400
|
|
|
327
401
|
export interface LargeFiles {
|
|
@@ -373,8 +447,50 @@ export interface LargeFiles {
|
|
|
373
447
|
prepare(ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext>;
|
|
374
448
|
/** Tools scoped to these documents. Pass `generate` to enable whole-document analysis. */
|
|
375
449
|
tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
|
|
450
|
+
/**
|
|
451
|
+
* Counters for metrics and alerts, read without a store call and without waiting. Optional, so
|
|
452
|
+
* that a `LargeFiles` of your own still compiles; the one `createLargeFiles` makes has it. New in
|
|
453
|
+
* 0.10.0.
|
|
454
|
+
*/
|
|
455
|
+
stats?(): LargeFilesStats;
|
|
456
|
+
/**
|
|
457
|
+
* Looks each ID up for `options.access`, as `getMeta` does, then makes the tools for the
|
|
458
|
+
* documents found (`tools`, with `access`): `missing` lists the others, those of another owner or
|
|
459
|
+
* scope included. A repeated ID counts once. Optional, so that a `LargeFiles` of your own still
|
|
460
|
+
* compiles; the one `createLargeFiles` makes has it. New in 0.10.0.
|
|
461
|
+
*/
|
|
462
|
+
toolsFor?(ids: string[], options: ToolOptions & { access: AccessOptions }): Promise<{ tools: ToolSet; missing: string[] }>;
|
|
376
463
|
}
|
|
377
464
|
|
|
465
|
+
/** What `files.stats()` counts: plain numbers, for metrics and alerts. New in 0.10.0. */
|
|
466
|
+
export type LargeFilesStats = {
|
|
467
|
+
/** Ingests doing their work, and those waiting their turn (`maxConcurrentIngests`). */
|
|
468
|
+
ingests: { active: number; waiting: number };
|
|
469
|
+
/** Scans of whole documents read by range, and those waiting their turn (`maxConcurrentScans`). */
|
|
470
|
+
scans: { active: number; waiting: number };
|
|
471
|
+
/** Looks at pages, and those waiting their turn (`maxConcurrentPageLooks`). */
|
|
472
|
+
pageLooks: { active: number; waiting: number };
|
|
473
|
+
/**
|
|
474
|
+
* What is kept in memory: its bytes, how many entries (documents, and pieces of documents read by
|
|
475
|
+
* range), and the most bytes they may take (`cacheBytes`).
|
|
476
|
+
*/
|
|
477
|
+
cache: { bytes: number; entries: number; maxBytes: number };
|
|
478
|
+
/**
|
|
479
|
+
* Calls of this process that ran past their time limit and have not settled: the store calls of
|
|
480
|
+
* every library (past `storeTimeoutMs`, or for `ingest` past `ingestTimeoutMs`), and the calls to
|
|
481
|
+
* the disk of the upload handlers (`uploadIdleTimeoutMs`).
|
|
482
|
+
*/
|
|
483
|
+
stuckStoreCalls: number;
|
|
484
|
+
/** This library's limit on them (`maxStuckStoreCalls`). */
|
|
485
|
+
maxStuckStoreCalls: number;
|
|
486
|
+
};
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* What `createLargeFiles` returns: a `LargeFiles` whose `stats` and `toolsFor` are always there, so
|
|
490
|
+
* that `files.stats()` needs no `?.`. New in 0.10.0.
|
|
491
|
+
*/
|
|
492
|
+
export type CreatedLargeFiles = LargeFiles & { stats(): LargeFilesStats; toolsFor: NonNullable<LargeFiles["toolsFor"]> };
|
|
493
|
+
|
|
378
494
|
/**
|
|
379
495
|
* Whether `value` has the shape of a document ID: one the library makes ("doc_" and 32 hex digits),
|
|
380
496
|
* or one an application may give (`APP_DOCUMENT_ID_PATTERN`, since 0.9.0), which the library's fit too.
|
|
@@ -393,14 +509,6 @@ function wholeName(meta: DocumentMeta): DocumentMeta {
|
|
|
393
509
|
return name === meta.name ? meta : { ...meta, name };
|
|
394
510
|
}
|
|
395
511
|
|
|
396
|
-
/**
|
|
397
|
-
* A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
|
|
398
|
-
* could not be read is not a document that is gone, and its own error names paths or hosts.
|
|
399
|
-
*/
|
|
400
|
-
function reading<T>(read: () => Promise<T>): Promise<T> {
|
|
401
|
-
return storeCall("read", read);
|
|
402
|
-
}
|
|
403
|
-
|
|
404
512
|
/** The key a caller's copy of a document is kept under in memory: the key of its scope, then the ID. */
|
|
405
513
|
const documentKey = (caller: Caller, id: string) => `${caller.key}\u0000${id}`;
|
|
406
514
|
|
|
@@ -439,6 +547,26 @@ export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
|
|
|
439
547
|
|
|
440
548
|
/** Default for `wholeDocumentBytes`. */
|
|
441
549
|
export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
|
|
550
|
+
/** Default for `storeTimeoutMs`: 30 seconds. */
|
|
551
|
+
export const DEFAULT_STORE_TIMEOUT_MS = 30_000;
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* Default for `maxStuckStoreCalls`: half of the threads of libuv's pool, and at least 1. The pool
|
|
555
|
+
* is read from `UV_THREADPOOL_SIZE` as libuv reads it (`atoi`): 4 when it is not set; its leading
|
|
556
|
+
* digits ("32abc" is 32); 1 thread for a value without them or for 0 ("", "x", "0"), which a
|
|
557
|
+
* template with an empty value gives; 1,024 at most, and for a value below 0, which libuv reads as
|
|
558
|
+
* a number without a sign, past the most.
|
|
559
|
+
*/
|
|
560
|
+
function defaultMaxStuck(): number {
|
|
561
|
+
const value = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.UV_THREADPOOL_SIZE;
|
|
562
|
+
let pool = 4;
|
|
563
|
+
if (value !== undefined) {
|
|
564
|
+
const given = Number.parseInt(value, 10);
|
|
565
|
+
pool = Number.isNaN(given) || given === 0 ? 1 : given < 0 ? 1_024 : Math.min(1_024, given);
|
|
566
|
+
}
|
|
567
|
+
return Math.max(1, Math.floor(pool / 2));
|
|
568
|
+
}
|
|
569
|
+
|
|
442
570
|
/** Looks at pages that run at once in a library, unless `maxConcurrentPageLooks` says otherwise. */
|
|
443
571
|
const DEFAULT_PAGE_LOOKS = 1;
|
|
444
572
|
/** How long a look at pages waits for its turn, unless `pageLookWaitMs` says otherwise. */
|
|
@@ -457,7 +585,7 @@ function numberOption(name: string, value: unknown, fallback: number, finite = f
|
|
|
457
585
|
return value;
|
|
458
586
|
}
|
|
459
587
|
|
|
460
|
-
export function createLargeFiles(options: LargeFilesOptions):
|
|
588
|
+
export function createLargeFiles(options: LargeFilesOptions): CreatedLargeFiles {
|
|
461
589
|
/** The fields the application set. The others follow the context window, whichever it is for a request. */
|
|
462
590
|
const ownBudget = givenBudget(options.budget);
|
|
463
591
|
const budget: Budget = resolveBudget(ownBudget);
|
|
@@ -504,19 +632,45 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
504
632
|
cache.deleteWhere((key) => keyOfId(key, id));
|
|
505
633
|
for (const key of rebuildIndex) if (keyOfId(key, id)) rebuildIndex.delete(key);
|
|
506
634
|
};
|
|
635
|
+
/** The most time one store call may take (`storeTimeoutMs`): 0 for no limit. */
|
|
636
|
+
const storeTimeoutMs = Math.max(0, numberOption("storeTimeoutMs", options.storeTimeoutMs, DEFAULT_STORE_TIMEOUT_MS));
|
|
637
|
+
/** The most time one sweep may take (`sweepTimeoutMs`): 0 for no limit. */
|
|
638
|
+
const sweepTimeoutMs = Math.max(0, numberOption("sweepTimeoutMs", options.sweepTimeoutMs, 0));
|
|
639
|
+
/** While this many calls of the process are stuck, store calls of this library fail at once (`maxStuckStoreCalls`). */
|
|
640
|
+
const maxStuckStoreCalls = Math.max(1, Math.trunc(numberOption("maxStuckStoreCalls", options.maxStuckStoreCalls, defaultMaxStuck())));
|
|
641
|
+
/**
|
|
642
|
+
* A call of the store, within `storeTimeoutMs`, refused at once while too many calls of the
|
|
643
|
+
* process are stuck. `signal` ends the caller's wait, never the call: a call that other callers
|
|
644
|
+
* wait on too (an opening of a document) is given none.
|
|
645
|
+
*/
|
|
646
|
+
const timed = <T>(operation: DocumentStoreOperation, call: () => Promise<T>, signal?: AbortSignal): Promise<T> => (
|
|
647
|
+
storeCall(operation, call, { timeoutMs: storeTimeoutMs, maxStuck: maxStuckStoreCalls, signal })
|
|
648
|
+
);
|
|
649
|
+
/**
|
|
650
|
+
* A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
|
|
651
|
+
* could not be read is not a document that is gone, and its own error names paths or hosts.
|
|
652
|
+
*/
|
|
653
|
+
const reading = <T>(read: () => Promise<T>, signal?: AbortSignal): Promise<T> => timed("read", read, signal);
|
|
507
654
|
/** Documents being opened, so that calls arriving together open each one once. */
|
|
508
655
|
const opening = new Map<string, Promise<DocumentSource | undefined>>();
|
|
509
656
|
/**
|
|
510
657
|
* The store, to read the text of a document by range rather than load it whole: each call carries
|
|
511
658
|
* `context`: the caller's scope, and the document's owner when it has one (`documentContext`).
|
|
659
|
+
* A document read by range is shared by every caller of its scope: its reads have a time limit,
|
|
660
|
+
* and no caller's signal.
|
|
512
661
|
*/
|
|
513
662
|
const rangeStore = (context: DocumentContext): RangeStore => ({
|
|
514
663
|
readTextRange: (id, start, end) => reading(() => store.readTextRange!(id, start, end, context)),
|
|
515
664
|
...(store.getIndex ? { getIndex: (id: string) => reading(() => store.getIndex!(id, context)) } : {}),
|
|
516
|
-
...(store.putIndex ? { putIndex: (id: string, index: Uint8Array) => store.putIndex!(id, index, context) } : {}),
|
|
665
|
+
...(store.putIndex ? { putIndex: (id: string, index: Uint8Array) => timed("write", () => store.putIndex!(id, index, context)) } : {}),
|
|
517
666
|
});
|
|
518
667
|
/** The uploaded file of a document, when the store keeps such files. */
|
|
519
|
-
const loadOriginal = (id: string, context: DocumentContext) => reading(() => store.getOriginal!(id, context));
|
|
668
|
+
const loadOriginal = (id: string, context: DocumentContext, signal?: AbortSignal) => reading(() => store.getOriginal!(id, context), signal);
|
|
669
|
+
/**
|
|
670
|
+
* Removals of documents (`delete`) take their turns, one at a time: a store that does not answer
|
|
671
|
+
* then holds one thread of the pool for them, not one for each.
|
|
672
|
+
*/
|
|
673
|
+
const removals = new Limiter(1);
|
|
520
674
|
const wholeDocumentBytes = Math.max(0, numberOption("wholeDocumentBytes", options.wholeDocumentBytes, DEFAULT_WHOLE_DOCUMENT_BYTES));
|
|
521
675
|
/** Documents (by `documentKey`) whose saved index did not match their text: the next opening builds it from the text. */
|
|
522
676
|
const rebuildIndex = new Set<string>();
|
|
@@ -584,6 +738,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
584
738
|
},
|
|
585
739
|
ingests,
|
|
586
740
|
slotCapMs,
|
|
741
|
+
maxStuck: maxStuckStoreCalls,
|
|
587
742
|
keeps,
|
|
588
743
|
readsRefs: originals !== undefined,
|
|
589
744
|
forget,
|
|
@@ -598,7 +753,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
598
753
|
*/
|
|
599
754
|
async function currentMeta(id: string, caller: Caller): Promise<DocumentMeta | undefined> {
|
|
600
755
|
if (!isDocumentId(id)) return undefined;
|
|
601
|
-
const meta = metaOf(await reading(() => store.getMeta(id, caller.context)), id);
|
|
756
|
+
const meta = metaOf(await reading(() => store.getMeta(id, caller.context), caller.signal), id);
|
|
602
757
|
if (meta) checkMetaVersion(meta);
|
|
603
758
|
if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
|
|
604
759
|
forgetKey(documentKey(caller, id));
|
|
@@ -616,7 +771,9 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
616
771
|
/**
|
|
617
772
|
* A document ready to read and search, for `caller`, who may use it. The store is asked first,
|
|
618
773
|
* every time: a kept copy is used only while the store still has the same document. `known` is
|
|
619
|
-
* metadata just read from the store and checked, to save asking twice.
|
|
774
|
+
* metadata just read from the store and checked, to save asking twice. One opening serves every
|
|
775
|
+
* caller of the scope who asks meanwhile: its reads have time limits, and each caller stops
|
|
776
|
+
* waiting for it when its own signal aborts, which leaves the others waiting (0.10.0).
|
|
620
777
|
*/
|
|
621
778
|
async function load(id: string, caller: Caller, known?: DocumentMeta): Promise<DocumentSource | undefined> {
|
|
622
779
|
const meta = known ?? await metaFor(id, caller);
|
|
@@ -628,12 +785,16 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
628
785
|
const opened = `${key}|${version}`;
|
|
629
786
|
let pending = opening.get(opened);
|
|
630
787
|
if (!pending) {
|
|
631
|
-
|
|
788
|
+
// Kept once opened, whether or not a caller still waits for it.
|
|
789
|
+
pending = open(id, meta, caller, key)
|
|
790
|
+
.then((document) => {
|
|
791
|
+
if (document) cache.set(key, version, document);
|
|
792
|
+
return document;
|
|
793
|
+
})
|
|
794
|
+
.finally(() => opening.delete(opened));
|
|
632
795
|
opening.set(opened, pending);
|
|
633
796
|
}
|
|
634
|
-
|
|
635
|
-
if (document) cache.set(key, version, document);
|
|
636
|
-
return document;
|
|
797
|
+
return until(pending, caller.signal);
|
|
637
798
|
}
|
|
638
799
|
|
|
639
800
|
/**
|
|
@@ -680,11 +841,11 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
680
841
|
if (kept) {
|
|
681
842
|
if (!originals) return "missing";
|
|
682
843
|
const context: OriginalReadContext = Object.freeze({ ...caller.context, id, bytes: kept.bytes });
|
|
683
|
-
read = await reading(() => originals.read(kept.ref, context));
|
|
844
|
+
read = await reading(() => originals.read(kept.ref, context), caller.signal);
|
|
684
845
|
} else {
|
|
685
846
|
if (meta.original !== undefined && meta.original !== null) return "missing";
|
|
686
847
|
if (!store.getOriginal) return "missing";
|
|
687
|
-
read = await loadOriginal(id, caller.context);
|
|
848
|
+
read = await loadOriginal(id, caller.context, caller.signal);
|
|
688
849
|
}
|
|
689
850
|
if (!read) return "missing";
|
|
690
851
|
const bytes = read;
|
|
@@ -715,30 +876,102 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
715
876
|
}
|
|
716
877
|
|
|
717
878
|
/**
|
|
718
|
-
*
|
|
719
|
-
*
|
|
879
|
+
* Removes a document from the store (`store.delete`), in the removals' turn (`removals`). The turn
|
|
880
|
+
* and the store call are waited for until `deadline` aborts (the delete's time limit, which they
|
|
881
|
+
* share), or the caller's signal does; the turn is then held until the store call ends, even past
|
|
882
|
+
* its time limit. The store call counts as stuck once it has itself run `storeTimeoutMs`.
|
|
720
883
|
*/
|
|
721
|
-
async function
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
884
|
+
async function removal(call: () => Promise<boolean>, signal: AbortSignal | undefined, deadline: AbortSignal): Promise<boolean> {
|
|
885
|
+
checkStuck("delete", maxStuckStoreCalls);
|
|
886
|
+
if (signal?.aborted) throw signal.reason;
|
|
887
|
+
if (deadline.aborted) throw deadline.reason;
|
|
888
|
+
const waits = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
889
|
+
let release: () => void;
|
|
890
|
+
try {
|
|
891
|
+
release = await removals.acquire(waits);
|
|
892
|
+
} catch (error) {
|
|
893
|
+
if (signal?.aborted) throw signal.reason;
|
|
894
|
+
throw deadline.aborted ? deadline.reason : error;
|
|
895
|
+
}
|
|
896
|
+
let started = false;
|
|
897
|
+
try {
|
|
898
|
+
return await timed("delete", () => {
|
|
899
|
+
started = true;
|
|
900
|
+
let running: Promise<boolean>;
|
|
901
|
+
try {
|
|
902
|
+
running = Promise.resolve(call());
|
|
903
|
+
} catch (error) {
|
|
904
|
+
running = Promise.reject(error);
|
|
905
|
+
}
|
|
906
|
+
running.then(release, release);
|
|
907
|
+
return running;
|
|
908
|
+
}, waits);
|
|
909
|
+
} finally {
|
|
910
|
+
if (!started) release();
|
|
740
911
|
}
|
|
741
|
-
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/** What planning a request (`prepareDocuments`, src/prepare.ts) needs of this library. */
|
|
915
|
+
const planning: PrepareContext = { callerOf: (access) => callerOf(access, rules), metaFor, load, stillOpened, budgetFor, viewableMeta, rules };
|
|
916
|
+
|
|
917
|
+
/** `files.tools`: the tools for `documents`. */
|
|
918
|
+
function tools(documents: DocumentMeta[], toolOptions: ToolOptions = {}): ToolSet {
|
|
919
|
+
const { viewPages, budget: overrides, access, ...rest } = toolOptions;
|
|
920
|
+
// Without `access`, the owner and scope of each document are those it was handed in with: a
|
|
921
|
+
// library that requires them takes them only from the caller.
|
|
922
|
+
if (access === undefined && (rules.requireOwner || rules.requireScope)) {
|
|
923
|
+
throw new TypeError(rules.requireOwner ? OWNER_REQUIRED : SCOPE_REQUIRED);
|
|
924
|
+
}
|
|
925
|
+
// The tool set's signal ends its waits for the store too, unless `access` has a signal of its own.
|
|
926
|
+
// It is taken as it is, as before 0.10.0 (an object made like an AbortSignal too): only
|
|
927
|
+
// `access.signal`, new in 0.10.0, must be an AbortSignal (`callerOf`).
|
|
928
|
+
const signal = access?.signal ?? toolOptions.signal;
|
|
929
|
+
const asker = access !== undefined ? withSignal(callerOf(access, rules), signal) : undefined;
|
|
930
|
+
const budget = budgetFor(overrides);
|
|
931
|
+
// Which PDFs can be looked at, by the metadata handed in: each look reads the metadata the
|
|
932
|
+
// store holds, and the file it names, not the one handed in.
|
|
933
|
+
const viewable = (viewPages === true ? documents : viewPages || []).filter(viewableMeta);
|
|
934
|
+
// Without `access`, as before 0.9.0: the owner and scope each document was handed in with.
|
|
935
|
+
// The store is asked with them, and the owner and scope it holds are checked against them on
|
|
936
|
+
// every call, so metadata built from an ID alone cannot read another owner's document: such a
|
|
937
|
+
// document is answered as no longer available, as `getMeta` reports it missing. A handed scope
|
|
938
|
+
// that is not valid reads nothing.
|
|
939
|
+
const handed = new Map<string, Caller | undefined>(asker ? [] : [...documents, ...viewable].map((meta) => [meta.id, handedCaller(meta, signal)]));
|
|
940
|
+
const noCaller = signal ? { ...NO_CALLER, signal } : NO_CALLER;
|
|
941
|
+
const callerFor = (id: string): Caller | undefined => asker ?? (handed.has(id) ? handed.get(id) : noCaller);
|
|
942
|
+
// The metadata the store holds now, not that of a copy kept in memory.
|
|
943
|
+
const checkedLoad = async (id: string) => {
|
|
944
|
+
const caller = callerFor(id);
|
|
945
|
+
const meta = caller && await metaFor(id, caller);
|
|
946
|
+
return meta ? load(id, caller, meta) : undefined;
|
|
947
|
+
};
|
|
948
|
+
const checkedOriginal = (store.getOriginal || originals) && (async (id: string) => {
|
|
949
|
+
const caller = callerFor(id);
|
|
950
|
+
const meta = caller && await metaFor(id, caller);
|
|
951
|
+
if (!meta || !readable(meta)) return undefined;
|
|
952
|
+
const original = await originalOf(id, caller, meta);
|
|
953
|
+
// A file the application keeps that has changed since it was ingested: its pages are not
|
|
954
|
+
// those of the text the model has, and the model is told so.
|
|
955
|
+
if (original === "changed") throw new Error(changedOriginal(meta.name));
|
|
956
|
+
return original === "missing" ? undefined : original;
|
|
957
|
+
});
|
|
958
|
+
return createDocumentTools({
|
|
959
|
+
load: checkedLoad,
|
|
960
|
+
// Once a call has read a document by range: the store is asked again (`stillOpened`).
|
|
961
|
+
checkRead: async (document) => {
|
|
962
|
+
const caller = callerFor(document.meta.id);
|
|
963
|
+
return caller !== undefined && await stillOpened(document, caller);
|
|
964
|
+
},
|
|
965
|
+
documentIds: documents.map((meta) => meta.id),
|
|
966
|
+
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
967
|
+
budget,
|
|
968
|
+
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal, pageLooks } : {}),
|
|
969
|
+
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
970
|
+
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
971
|
+
// `aggregate_table` only when one may hold a table.
|
|
972
|
+
tables: documents.some((meta) => TABLE_FORMATS.has(meta.format)),
|
|
973
|
+
...rest,
|
|
974
|
+
});
|
|
742
975
|
}
|
|
743
976
|
|
|
744
977
|
return {
|
|
@@ -765,120 +998,81 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
765
998
|
|
|
766
999
|
async delete(id, access) {
|
|
767
1000
|
const caller = callerOf(access, rules);
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
1001
|
+
// One time limit for the whole delete: the look-up (which keeps its own, and its error of a
|
|
1002
|
+
// read), then the wait for the removals' turn and the store's delete. Before, the turn and the
|
|
1003
|
+
// delete had one each: with a slow delete before it, a delete answered after twice the limit.
|
|
1004
|
+
const deadline = new AbortController();
|
|
1005
|
+
const timer = isTimeLimit(storeTimeoutMs) ? setTimeout(() => deadline.abort(storeTimeout("delete", storeTimeoutMs)), storeTimeoutMs) : undefined;
|
|
1006
|
+
try {
|
|
1007
|
+
if (!await metaFor(id, caller)) return false;
|
|
1008
|
+
forget(id);
|
|
1009
|
+
return await removal(() => store.delete(id, caller.context), caller.signal, deadline.signal);
|
|
1010
|
+
} finally {
|
|
1011
|
+
clearTimeout(timer);
|
|
1012
|
+
}
|
|
771
1013
|
},
|
|
772
1014
|
|
|
773
1015
|
async sweep(sweepOptions) {
|
|
774
1016
|
// Upkeep of the store, not a user's access: allowed without a scope under `requireScope`.
|
|
775
1017
|
const scope = checkScope(sweepOptions?.scope ?? undefined);
|
|
776
1018
|
if (typeof store.sweep !== "function") return 0;
|
|
777
|
-
|
|
1019
|
+
// Within its own time limit, and never counted as stuck: a sweep of a large volume may take
|
|
1020
|
+
// long. It is refused, as other calls are, while too many calls are stuck.
|
|
1021
|
+
return storeCall("sweep", () => store.sweep!(now(), storeContext(scope, undefined)), { timeoutMs: sweepTimeoutMs, maxStuck: maxStuckStoreCalls, counts: false });
|
|
778
1022
|
},
|
|
779
1023
|
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
1024
|
+
// The options go on whole: planning (src/prepare.ts) reads the ones it knows.
|
|
1025
|
+
prepare(ids, base, prepareOptions) {
|
|
1026
|
+
return prepareDocuments(planning, ids, base, prepareOptions);
|
|
1027
|
+
},
|
|
1028
|
+
|
|
1029
|
+
tools,
|
|
1030
|
+
|
|
1031
|
+
stats() {
|
|
1032
|
+
// Counters only: no store call, no turn waited for.
|
|
1033
|
+
return {
|
|
1034
|
+
ingests: ingests.load,
|
|
1035
|
+
scans: scan.limiter.load,
|
|
1036
|
+
pageLooks: pageLooks.limiter.load,
|
|
1037
|
+
cache: { bytes: cache.bytes, entries: cache.size, maxBytes: cacheBytes },
|
|
1038
|
+
stuckStoreCalls: stuckCalls(),
|
|
1039
|
+
maxStuckStoreCalls,
|
|
1040
|
+
};
|
|
1041
|
+
},
|
|
1042
|
+
|
|
1043
|
+
async toolsFor(ids, toolOptions) {
|
|
1044
|
+
const access: unknown = toolOptions?.access;
|
|
1045
|
+
if (typeof access !== "object" || access === null) throw new TypeError("toolsFor needs options.access: the owner and scope of the caller, such as { owner: userId }.");
|
|
1046
|
+
if (!Array.isArray(ids)) throw new TypeError("toolsFor needs an array of document IDs.");
|
|
1047
|
+
const caller = withSignal(callerOf(toolOptions.access, rules), toolOptions.access.signal ?? toolOptions.signal);
|
|
1048
|
+
const found: DocumentMeta[] = [];
|
|
786
1049
|
const missing: string[] = [];
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
// not read at all.
|
|
1050
|
+
// One look-up at a time: a store that does not answer holds one thread of the pool, not one for each ID.
|
|
1051
|
+
for (const id of new Set<string>(ids)) {
|
|
790
1052
|
const meta = await metaFor(id, caller);
|
|
791
|
-
if (meta)
|
|
1053
|
+
if (meta) found.push(meta);
|
|
792
1054
|
else missing.push(id);
|
|
793
1055
|
}
|
|
794
|
-
|
|
795
|
-
// first lines for the others. One that is gone by then is missing, and the plan is made again.
|
|
796
|
-
for (;;) {
|
|
797
|
-
const plan = planDocuments(documents, budget, base);
|
|
798
|
-
const inline = new Set(plan.inline.map((meta) => meta.id));
|
|
799
|
-
// Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
|
|
800
|
-
const viewable = access?.viewPages ? documents.filter(viewableMeta) : [];
|
|
801
|
-
const shown = new Set(viewable.map((meta) => meta.id));
|
|
802
|
-
const blocks = new Map<string, string>();
|
|
803
|
-
const gone: string[] = [];
|
|
804
|
-
for (const meta of documents) {
|
|
805
|
-
const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
|
|
806
|
-
const text = await block(meta.id, meta, caller, inline.has(meta.id), shown.has(meta.id), wholeRead);
|
|
807
|
-
if (text === undefined) gone.push(meta.id);
|
|
808
|
-
else blocks.set(meta.id, text);
|
|
809
|
-
}
|
|
810
|
-
if (gone.length === 0) {
|
|
811
|
-
// A whole-document read is named only when the tools have it, and one of the files is
|
|
812
|
-
// small enough for it.
|
|
813
|
-
const wholeReads = analysis && plan.searchable.some((meta) => canBeReadWhole(meta, budget));
|
|
814
|
-
return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads), missing, viewable };
|
|
815
|
-
}
|
|
816
|
-
missing.push(...gone);
|
|
817
|
-
documents = documents.filter((meta) => !gone.includes(meta.id));
|
|
818
|
-
}
|
|
819
|
-
},
|
|
820
|
-
|
|
821
|
-
tools(documents, toolOptions = {}) {
|
|
822
|
-
const { viewPages, budget: overrides, access, ...rest } = toolOptions;
|
|
823
|
-
// Without `access`, the owner and scope of each document are those it was handed in with: a
|
|
824
|
-
// library that requires them takes them only from the caller.
|
|
825
|
-
if (access === undefined && (rules.requireOwner || rules.requireScope)) {
|
|
826
|
-
throw new TypeError(rules.requireOwner ? OWNER_REQUIRED : SCOPE_REQUIRED);
|
|
827
|
-
}
|
|
828
|
-
const asker = access !== undefined ? callerOf(access, rules) : undefined;
|
|
829
|
-
const budget = budgetFor(overrides);
|
|
830
|
-
// Which PDFs can be looked at, by the metadata handed in: each look reads the metadata the
|
|
831
|
-
// store holds, and the file it names, not the one handed in.
|
|
832
|
-
const viewable = (viewPages === true ? documents : viewPages || []).filter(viewableMeta);
|
|
833
|
-
// Without `access`, as before 0.9.0: the owner and scope each document was handed in with.
|
|
834
|
-
// The store is asked with them, and the owner and scope it holds are checked against them on
|
|
835
|
-
// every call, so metadata built from an ID alone cannot read another owner's document: such a
|
|
836
|
-
// document is answered as no longer available, as `getMeta` reports it missing. A handed scope
|
|
837
|
-
// that is not valid reads nothing.
|
|
838
|
-
const handed = new Map<string, Caller | undefined>(asker ? [] : [...documents, ...viewable].map((meta) => [meta.id, handedCaller(meta)]));
|
|
839
|
-
const callerFor = (id: string): Caller | undefined => asker ?? (handed.has(id) ? handed.get(id) : NO_CALLER);
|
|
840
|
-
// The metadata the store holds now, not that of a copy kept in memory.
|
|
841
|
-
const checkedLoad = async (id: string) => {
|
|
842
|
-
const caller = callerFor(id);
|
|
843
|
-
const meta = caller && await metaFor(id, caller);
|
|
844
|
-
return meta ? load(id, caller, meta) : undefined;
|
|
845
|
-
};
|
|
846
|
-
const checkedOriginal = (store.getOriginal || originals) && (async (id: string) => {
|
|
847
|
-
const caller = callerFor(id);
|
|
848
|
-
const meta = caller && await metaFor(id, caller);
|
|
849
|
-
if (!meta || !readable(meta)) return undefined;
|
|
850
|
-
const original = await originalOf(id, caller, meta);
|
|
851
|
-
// A file the application keeps that has changed since it was ingested: its pages are not
|
|
852
|
-
// those of the text the model has, and the model is told so.
|
|
853
|
-
if (original === "changed") throw new Error(changedOriginal(meta.name));
|
|
854
|
-
return original === "missing" ? undefined : original;
|
|
855
|
-
});
|
|
856
|
-
return createDocumentTools({
|
|
857
|
-
load: checkedLoad,
|
|
858
|
-
// Once a call has read a document by range: the store is asked again (`stillOpened`).
|
|
859
|
-
checkRead: async (document) => {
|
|
860
|
-
const caller = callerFor(document.meta.id);
|
|
861
|
-
return caller !== undefined && await stillOpened(document, caller);
|
|
862
|
-
},
|
|
863
|
-
documentIds: documents.map((meta) => meta.id),
|
|
864
|
-
names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
|
|
865
|
-
budget,
|
|
866
|
-
...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal, pageLooks } : {}),
|
|
867
|
-
// `analyze_whole_document` is declared only when it can read at least one of the documents.
|
|
868
|
-
wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
|
|
869
|
-
// `aggregate_table` only when one may hold a table.
|
|
870
|
-
tables: documents.some((meta) => TABLE_FORMATS.has(meta.format)),
|
|
871
|
-
...rest,
|
|
872
|
-
});
|
|
1056
|
+
return { tools: tools(found, toolOptions), missing };
|
|
873
1057
|
},
|
|
874
1058
|
};
|
|
875
1059
|
|
|
876
|
-
/**
|
|
877
|
-
|
|
1060
|
+
/**
|
|
1061
|
+
* The caller a document was handed to `tools` for (without `access`): its owner and scope, and the
|
|
1062
|
+
* tool set's signal. Undefined for a scope that is not valid: only that reads as missing.
|
|
1063
|
+
*/
|
|
1064
|
+
function handedCaller(meta: DocumentMeta, signal: AbortSignal | undefined): Caller | undefined {
|
|
1065
|
+
let caller: Caller;
|
|
878
1066
|
try {
|
|
879
|
-
|
|
1067
|
+
caller = callerOf({ owner: meta.owner, scope: meta.scope }, rules);
|
|
880
1068
|
} catch {
|
|
881
1069
|
return undefined;
|
|
882
1070
|
}
|
|
1071
|
+
return withSignal(caller, signal);
|
|
883
1072
|
}
|
|
884
1073
|
}
|
|
1074
|
+
|
|
1075
|
+
/** `caller`, whose waits for the store end when `signal` aborts. */
|
|
1076
|
+
function withSignal(caller: Caller, signal: AbortSignal | undefined): Caller {
|
|
1077
|
+
return signal === undefined ? caller : { ...caller, signal };
|
|
1078
|
+
}
|