llm-large-files 0.10.1 → 0.10.2
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 +75 -0
- package/dist/ask.d.ts +16 -0
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +26 -2
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +27 -1
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +96 -21
- package/dist/cache.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +12 -1
- package/dist/ingest.d.ts.map +1 -1
- package/dist/ingest.js +146 -11
- package/dist/ingest.js.map +1 -1
- package/dist/library.d.ts +55 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +74 -4
- package/dist/library.js.map +1 -1
- package/dist/stores.d.ts +38 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +184 -6
- package/dist/stores.js.map +1 -1
- package/dist/testing/store-checks.d.ts +8 -3
- package/dist/testing/store-checks.d.ts.map +1 -1
- package/dist/testing/store-checks.js +74 -1
- package/dist/testing/store-checks.js.map +1 -1
- package/dist/types.d.ts +56 -0
- package/dist/types.d.ts.map +1 -1
- package/docs/guides/deployment.md +3 -3
- package/docs/guides/storage.md +62 -8
- package/docs/reference/ask.md +25 -3
- package/docs/reference/events.md +1 -1
- package/docs/reference/library.md +106 -11
- package/docs/reference/testing.md +10 -4
- package/docs/security.md +2 -1
- package/package.json +1 -1
- package/src/ask.ts +35 -2
- package/src/cache.ts +95 -19
- package/src/index.ts +2 -2
- package/src/ingest.ts +144 -12
- package/src/library.ts +122 -8
- package/src/stores.ts +174 -7
- package/src/testing/store-checks.ts +74 -3
- package/src/types.ts +55 -0
|
@@ -8,7 +8,7 @@ an application or write a store, an extractor or a loop of their own.
|
|
|
8
8
|
```ts
|
|
9
9
|
import {
|
|
10
10
|
createLargeFiles, DEFAULT_CACHE_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, DEFAULT_MAX_PDF_PAGES, DEFAULT_MAX_TEXT_BYTES,
|
|
11
|
-
DEFAULT_INGEST_TIMEOUT_MS, NEVER_EXPIRES, isDocumentId, toDocumentSummary, IngestError, ingestErrorCodeOf,
|
|
11
|
+
DEFAULT_INGEST_TIMEOUT_MS, NEVER_EXPIRES, MAX_APP_DATA_BYTES, isDocumentId, toDocumentSummary, IngestError, ingestErrorCodeOf,
|
|
12
12
|
DEFAULT_BUDGET, resolveBudget,
|
|
13
13
|
MemoryDocumentStore, FileDocumentStore, isSafeScopeSegment, hashedScopeSegment,
|
|
14
14
|
DOCUMENT_ID_PATTERN, APP_DOCUMENT_ID_PATTERN, DOCUMENT_META_VERSION,
|
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
ExtractedText, DocumentMeta, DocumentSummary, DocumentFormat, OutlineEntry, LogIssue, LogProfile, ProgressEvent,
|
|
25
25
|
ProgressListener, ToolCallHooks, ToolRequestHandle, ToolRequestStart, ToolRequestEnd, IngestEvent, IngestErrorCode,
|
|
26
26
|
DocumentStoreOperation, DocumentScopeErrorCode,
|
|
27
|
+
AppData, JsonValue, MetaPatch, // new in 0.10.2
|
|
27
28
|
} from "llm-large-files";
|
|
28
29
|
```
|
|
29
30
|
|
|
@@ -144,7 +145,7 @@ type LargeFilesOptions = {
|
|
|
144
145
|
| `keepOriginals` | `DocumentFormat[]` | `[]` | Formats whose uploaded file is kept, for example `["pdf"]`, which `view_pages` needs: as a copy in the store, next to its text, when the store has `putOriginal`; or, for an ingest with `IngestInput.original` (new in 0.9.0), where your application keeps it, read back through `originals`. A copy takes as much space as the upload until its document expires or is deleted. |
|
|
145
146
|
| `originals` | [`OriginalsReader`](#originalsreader) | none | Reads the uploaded files your application keeps itself, by the ref given at ingest (`IngestInput.original`), in place of a copy in the store: `fileOriginals(root)` of [`llm-large-files/node`](./node.md#fileoriginalsroot), or your own. Each read is checked against the size and SHA-256 the file had at ingest. Without it, an ingest with `original` throws a `TypeError`. Not an object with a `read` method: a `TypeError` when the library is made. New in 0.9.0. |
|
|
146
147
|
| `scannedPdfPages` | `number` | 30 | The most pages a PDF without any text (a scan) may have and still be accepted, so that its pages can be shown to the model. It applies only when `"pdf"` is in `keepOriginals` and the file is kept: the store has `putOriginal`, or (0.9.0) the ingest gives `original` and the library has `originals`. Otherwise, and with 0, such a PDF is refused. Your own PDF extractor receives it as `ExtractInput.scannedPages`. |
|
|
147
|
-
| `cacheBytes` | `number` | [`DEFAULT_CACHE_BYTES`](#default_cache_bytes), 256 MB | The most memory that documents kept ready between tool calls may take, together with the decoded pieces of documents read by range. The least recently used go first. A document that would take more than this is not kept
|
|
148
|
+
| `cacheBytes` | `number` | [`DEFAULT_CACHE_BYTES`](#default_cache_bytes), 256 MB | The most memory that documents kept ready between tool calls may take, together with the decoded pieces of documents read by range. The least recently used go first. A document that would take more than this is not kept with the others: since 0.10.2 the last one is kept apart, one at most and on top of this limit, for a minute after its last use (P4; `stats().cache.bytes` counts it, `entries` does not), so the tool calls of a question do not each load and index it again (before, it was read again for each call; that matters over a store without `readTextRange`). A document whose decoded text would take more than a quarter of it keeps no pieces. 0 keeps nothing. Each use of a kept document asks the store first, so a document deleted or expired on another server is never served from memory. |
|
|
148
149
|
| `cacheSize` | `number` | no limit | Also caps the number of documents kept. The pieces of a document read by range are not counted, and leave with their document. 0 keeps nothing. |
|
|
149
150
|
| `wholeDocumentBytes` | `number` | [`DEFAULT_WHOLE_DOCUMENT_BYTES`](#default_whole_document_bytes), 2 MB | Documents whose text (`textBytes`) is at most this size are loaded whole into memory. Larger ones are read by range when the store has `readTextRange`, as `FileDocumentStore` does: a tool call reads only the lines it needs, and a search reads the text a piece at a time. `Infinity` loads every document whole; 0 reads every one by range. |
|
|
150
151
|
| `scanChunkBytes` | `number` | 1 MB (1,048,576) | Reading by range: about how many bytes of text are read and searched at a time. At least 1. |
|
|
@@ -154,8 +155,8 @@ type LargeFilesOptions = {
|
|
|
154
155
|
| `pageLookWaitMs` | `number` | 30,000 | How long a look at pages waits for its turn, in milliseconds. Past it, the look is not run: the model reads "‹file›: The pages cannot be looked at right now; the server is busy. Answer from the text, or look again later.", and `askWithFiles` gives a `"page_looks_busy"` notice. A question that is stopped stops waiting at once. In `askWithFiles` a wait that ends busy comes once in a tool turn: after a look of the turn was told the server is busy, its other looks run only when a turn is free at once ([`ToolCallLimits.maxWaitMs`](./tools.md#toolcalllimits)). Each look that gets its turn may still have waited up to `pageLookWaitMs`: see [PDFs](../guides/pdfs.md). `Infinity` waits without end; 0 does not wait. New in 0.9.0. |
|
|
155
156
|
| `requireOwner` | `boolean` | `false` | Every call must name its owner: `ingest`, `getMeta`, `getOriginal`, `delete`, `prepare`, `askWithFiles`, `askStream` and `askGemini`, and `tools`, which then needs `access`. A call without one throws `TypeError("owner is required: requireOwner is on")`, before the store is asked anything. An owner that `ingest` would refuse (`""`, spaces only) is refused too. A document stored without an owner reads as missing. Use it on a server where every document belongs to a signed-in user: a call that forgot the owner fails, rather than reaching every document stored without one. New in 0.9.0. |
|
|
156
157
|
| `requireScope` | `boolean` | `false` | The same for scopes ([`DocumentScope`](#documentscope)): a call without one throws `TypeError("scope is required: requireScope is on")`, and a document stored without a scope reads as missing. `files.sweep()` without a scope is still allowed: it is upkeep, not a user's access. New in 0.9.0. |
|
|
157
|
-
| `storeTimeoutMs` | `number` | 30,000 | The most time one store call may take, in milliseconds: `getMeta`, `get`, `readTextRange`, `getIndex` and `putIndex` when a document is opened, `getOriginal` (and `originals.read`), and `delete`. Past it, the call fails with a [`DocumentStoreError`](#documentstoreerror) of code `"ETIMEDOUT"` (status 503, `cause`: `The store did not answer within 30 s.`). The call itself goes on, since nothing can stop it, and counts as stuck until it ends (`maxStuckStoreCalls`). In a question, a tool call that meets it ends the question with `run.error`. `ingest` keeps its own limits (`ingestTimeoutMs`), past which its store calls count as stuck too, and `sweep` has `sweepTimeoutMs`. Keep it above your store's slowest healthy call, such as a `get` of a text of `wholeDocumentBytes`. 0 sets no limit, and so does a time past what a timer can wait. Before 0.10.0 a store call that never settled held its caller forever. New in 0.10.0. [Storage](../guides/storage.md#time-limits). |
|
|
158
|
-
| `maxStuckStoreCalls` | `number` | half of `UV_THREADPOOL_SIZE` (4 when it is not set), at least 1: 2 by default, 16 with 32 threads | While this many calls of the process are stuck (past their time limit, and not ended), every new store call of this library fails at once, without calling the store, with a `DocumentStoreError` of code `"STORE_STUCK"` (status 503): an `ingest` fails at its first store call (operation `"write"`, or `"read"` for the look-up of an application's ID). The removal of what an ingest wrote, once writes that began under the limit end (its caller left, or they failed), still runs. The count is the process's, shared by every library: store calls past `storeTimeoutMs`, whether their caller timed out or left, the store calls of `ingest` past the time it gives them (`ingestTimeoutMs`, 2 minutes when it is 0), and the upload handlers' calls to the disk past `uploadIdleTimeoutMs`. A call that ends within its limit never counts. `UV_THREADPOOL_SIZE` is read when the library is made, as libuv reads it: an empty value, 0, or one that does not start with digits is a pool of 1 thread, so a limit of 1. `Infinity` refuses nothing. New in 0.10.0. [Deployment](../guides/deployment.md#a-store-that-stops-answering). |
|
|
158
|
+
| `storeTimeoutMs` | `number` | 30,000 | The most time one store call may take, in milliseconds: `getMeta`, `get`, `readTextRange`, `getIndex` and `putIndex` when a document is opened, `getOriginal` (and `originals.read`), and `delete`. Past it, the call fails with a [`DocumentStoreError`](#documentstoreerror) of code `"ETIMEDOUT"` (status 503, `cause`: `The store did not answer within 30 s.`). The call itself goes on, since nothing can stop it, and counts as stuck until it ends (`maxStuckStoreCalls`). In a question, a tool call that meets it ends the question with `run.error`. `ingest` keeps its own limits (`ingestTimeoutMs`), past which its store calls, and since 0.10.2 its own reads of a path upload, count as stuck too, and `sweep` has `sweepTimeoutMs`. Keep it above your store's slowest healthy call, such as a `get` of a text of `wholeDocumentBytes`. 0 sets no limit, and so does a time past what a timer can wait. Before 0.10.0 a store call that never settled held its caller forever. New in 0.10.0. [Storage](../guides/storage.md#time-limits). |
|
|
159
|
+
| `maxStuckStoreCalls` | `number` | half of `UV_THREADPOOL_SIZE` (4 when it is not set), at least 1: 2 by default, 16 with 32 threads | While this many calls of the process are stuck (past their time limit, and not ended), every new store call of this library fails at once, without calling the store, with a `DocumentStoreError` of code `"STORE_STUCK"` (status 503): an `ingest` fails at its first store call (operation `"write"`, or `"read"` for the look-up of an application's ID). The removal of what an ingest wrote, once writes that began under the limit end (its caller left, or they failed), still runs. The count is the process's, shared by every library: store calls past `storeTimeoutMs`, whether their caller timed out or left, the store calls of `ingest` past the time it gives them (`ingestTimeoutMs`, 2 minutes when it is 0), since 0.10.2 its own reads of a path upload (its `lstat` and format reads past that time, and the read of the file when `ingestTimeoutMs` is a time limit), and the upload handlers' calls to the disk past `uploadIdleTimeoutMs`. A call that ends within its limit never counts. `UV_THREADPOOL_SIZE` is read when the library is made, as libuv reads it: an empty value, 0, or one that does not start with digits is a pool of 1 thread, so a limit of 1. `Infinity` refuses nothing. New in 0.10.0. [Deployment](../guides/deployment.md#a-store-that-stops-answering). |
|
|
159
160
|
| `sweepTimeoutMs` | `number` | 0 (no limit) | The most time one `sweep` may take, in milliseconds. Past it, `sweep` fails with a `DocumentStoreError` of operation `"sweep"` and code `"ETIMEDOUT"`, and the sweep goes on. A sweep never counts as a stuck call; while `maxStuckStoreCalls` calls are stuck, it is refused at once, as other store calls are. New in 0.10.0. |
|
|
160
161
|
| `now` | `() => Date` | `() => new Date()` | The clock, for tests. It dates `createdAt` and `expiresAt`, decides whether a document has expired, and is passed to the store's `sweep`. |
|
|
161
162
|
|
|
@@ -194,6 +195,9 @@ interface LargeFiles {
|
|
|
194
195
|
tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
|
|
195
196
|
stats?(): LargeFilesStats; // new in 0.10.0
|
|
196
197
|
toolsFor?(ids: string[], options: ToolOptions & { access: AccessOptions }): Promise<{ tools: ToolSet; missing: string[] }>; // new in 0.10.0
|
|
198
|
+
list?(access?: AccessOptions): Promise<DocumentMeta[]>; // new in 0.10.2
|
|
199
|
+
touch?(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>; // new in 0.10.2
|
|
200
|
+
update?(id: string, changes: { appData?: object | null }, access?: AccessOptions): Promise<DocumentMeta | undefined>; // new in 0.10.2
|
|
197
201
|
}
|
|
198
202
|
```
|
|
199
203
|
|
|
@@ -221,6 +225,14 @@ The members new in 0.10.0:
|
|
|
221
225
|
| `stats` | `() => LargeFilesStats`, optional | Counters for metrics and alerts ([`files.stats()`](#filesstats)), read without a store call. Optional, so that a `LargeFiles` of your own still compiles; the one `createLargeFiles` makes has it. New in 0.10.0. |
|
|
222
226
|
| `toolsFor` | `(ids: string[], options: ToolOptions & { access: AccessOptions }) => Promise<{ tools: ToolSet; missing: string[] }>`, optional | Looks each ID up for `options.access`, then makes the tools for the documents found; `missing` lists the others ([`files.toolsFor()`](#filestoolsforids-options)). Optional, as `stats` is. New in 0.10.0. |
|
|
223
227
|
|
|
228
|
+
The members new in 0.10.2, optional for the same reason; the one `createLargeFiles` makes has them:
|
|
229
|
+
|
|
230
|
+
| Member | Type | What it is |
|
|
231
|
+
|---|---|---|
|
|
232
|
+
| `list` | `(access?: AccessOptions) => Promise<DocumentMeta[]>` | The documents of a scope the caller may use ([`files.list()`](#fileslistaccess)). |
|
|
233
|
+
| `touch` | `(id: string, access?: AccessOptions) => Promise<DocumentMeta \| undefined>` | Counts a document's expiry again from now ([`files.touch()`](#filestouchid-access)). |
|
|
234
|
+
| `update` | `(id: string, changes: { appData?: object \| null }, access?: AccessOptions) => Promise<DocumentMeta \| undefined>` | Changes the application's own data about a document ([`files.update()`](#filesupdateid-changes-access)). |
|
|
235
|
+
|
|
224
236
|
#### `files.access`
|
|
225
237
|
|
|
226
238
|
`readonly access?: { readonly requireOwner: boolean; readonly requireScope: boolean }`
|
|
@@ -577,6 +589,57 @@ async function chatTools(files: LargeFiles & { toolsFor: NonNullable<LargeFiles[
|
|
|
577
589
|
}
|
|
578
590
|
```
|
|
579
591
|
|
|
592
|
+
#### `files.list(access?)`
|
|
593
|
+
|
|
594
|
+
`list(access?: AccessOptions): Promise<DocumentMeta[]>`
|
|
595
|
+
|
|
596
|
+
New in 0.10.2. The documents held by exactly the caller's owner and scope, as
|
|
597
|
+
[`files.getMeta`](#filesgetmetaid-access) would give each: with `{ owner, scope }`, those stored with
|
|
598
|
+
that owner and that scope; without an owner, those without one; without a scope, those without
|
|
599
|
+
one. For a chat's file panel, with no second list of its files in your database. The oldest first,
|
|
600
|
+
then by ID. A document without an owner is never listed to a caller with one: anyone who has its
|
|
601
|
+
ID may use it (its ID works like a password, [Security](../security.md)), and a list would hand
|
|
602
|
+
those IDs to every user. Left out too: expired documents, metadata that is damaged or names another
|
|
603
|
+
ID, and metadata of a newer version of the package, where `getMeta` would throw `"NEWER_VERSION"`.
|
|
604
|
+
It reads the store once, through [`DocumentStore.list`](#documentstore): a store without it is a
|
|
605
|
+
`TypeError`. Under `requireOwner` and `requireScope` it needs the owner and the scope, as every
|
|
606
|
+
call does. A store that fails is a `DocumentStoreError` of operation `"read"`, within
|
|
607
|
+
`storeTimeoutMs`; `access.signal` ends the wait.
|
|
608
|
+
|
|
609
|
+
```ts
|
|
610
|
+
// The files of one chat, for its panel.
|
|
611
|
+
const shown = (await files.list!({ owner: userId, scope: [userId, chatId] })).map(toDocumentSummary);
|
|
612
|
+
```
|
|
613
|
+
|
|
614
|
+
#### `files.touch(id, access?)`
|
|
615
|
+
|
|
616
|
+
`touch(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>`
|
|
617
|
+
|
|
618
|
+
New in 0.10.2. Marks a document used: its `expiresAt` is counted again from now (`ttlMs`), so a
|
|
619
|
+
file that a chat still reads stays while one nobody reads goes at its time (H5). An expiry that is
|
|
620
|
+
already later stays as it is. Returns the metadata as it now is, or undefined when the document is
|
|
621
|
+
missing for this caller (never there, deleted, expired, of another owner or scope). Only the
|
|
622
|
+
expiry is changed, through [`DocumentStore.patchMeta`](#documentstore), and only for the document
|
|
623
|
+
the library just looked up (by its `createdAt`, owner and scope): one deleted and stored again under
|
|
624
|
+
the same ID meanwhile is not changed, and `touch` gives undefined. When the expiry is already as
|
|
625
|
+
late, nothing is written. A store without `patchMeta` is a
|
|
626
|
+
`TypeError`. The text, its index and its original are not touched, and a copy kept in memory stays
|
|
627
|
+
valid. A `touch` and an `update` at once both stay. A store that fails
|
|
628
|
+
is a `DocumentStoreError`. Call it when a question uses a document, for example after
|
|
629
|
+
`askWithFiles`, for each of its `documentIds`.
|
|
630
|
+
|
|
631
|
+
#### `files.update(id, changes, access?)`
|
|
632
|
+
|
|
633
|
+
`update(id: string, changes: { appData?: object | null }, access?: AccessOptions): Promise<DocumentMeta | undefined>`
|
|
634
|
+
|
|
635
|
+
New in 0.10.2. Changes the application's own data about a document,
|
|
636
|
+
[`DocumentMeta.appData`](#documentmeta), and nothing else: `appData` replaces it whole, `null`
|
|
637
|
+
removes it, and leaving it out changes nothing. The same checks as at ingest
|
|
638
|
+
([`IngestInput.appData`](#ingestinput)): a JSON object of at most `MAX_APP_DATA_BYTES` (16 KB) as
|
|
639
|
+
JSON; another field in `changes` is a `TypeError`. Returns the metadata as it now is, or undefined
|
|
640
|
+
when the document is missing for this caller, or was stored again under the ID meanwhile. It needs
|
|
641
|
+
[`DocumentStore.patchMeta`](#documentstore), as `touch` does.
|
|
642
|
+
|
|
580
643
|
#### `files.budget`
|
|
581
644
|
|
|
582
645
|
`readonly budget: Budget`
|
|
@@ -632,8 +695,8 @@ What `files.stats()` gives. New in 0.10.0.
|
|
|
632
695
|
| `ingests` | `{ active: number; waiting: number }` | Ingests doing their work, and those waiting their turn (`maxConcurrentIngests`). |
|
|
633
696
|
| `scans` | `{ active: number; waiting: number }` | Scans of whole documents read by range, and those waiting their turn (`maxConcurrentScans`). |
|
|
634
697
|
| `pageLooks` | `{ active: number; waiting: number }` | Looks at pages, and those waiting their turn (`maxConcurrentPageLooks`). |
|
|
635
|
-
| `cache` | `{ bytes: number; entries: number; maxBytes: number }` | What is kept in memory: its bytes, by their own estimate; how many entries, the documents and the decoded pieces of documents read by range; and the most bytes
|
|
636
|
-
| `stuckStoreCalls` | `number` | Calls of this process that ran past their time limit and have not settled: the store calls of every library (past `storeTimeoutMs`, or for `ingest` past `ingestTimeoutMs`),
|
|
698
|
+
| `cache` | `{ bytes: number; entries: number; maxBytes: number }` | What is kept in memory: its bytes, by their own estimate; how many entries, the documents and the decoded pieces of documents read by range; and `cacheBytes`, the most bytes those entries may take. Since 0.10.2, `bytes` also counts the last document larger than `cacheBytes`, kept apart on top of it (P4), which `entries` does not: `bytes` can be above `maxBytes`. |
|
|
699
|
+
| `stuckStoreCalls` | `number` | Calls of this process that ran past their time limit and have not settled: the store calls of every library (past `storeTimeoutMs`, or for `ingest` past `ingestTimeoutMs`), the upload handlers' calls to the disk (past `uploadIdleTimeoutMs`), and since 0.10.2 an ingest's own reads of a path upload (its `lstat` and format reads, and the read of the file when `ingestTimeoutMs` is a time limit). The same for every library of the process. |
|
|
637
700
|
| `maxStuckStoreCalls` | `number` | This library's limit on them (`maxStuckStoreCalls`): at it, its store calls fail at once with `"STORE_STUCK"`. |
|
|
638
701
|
|
|
639
702
|
### `IngestInput`
|
|
@@ -651,6 +714,8 @@ type IngestInput = {
|
|
|
651
714
|
ifExists?: "fail" | "replace"; // new in 0.9.0
|
|
652
715
|
scope?: DocumentScope; // new in 0.9.0
|
|
653
716
|
original?: { ref: string }; // new in 0.9.0
|
|
717
|
+
appData?: object; // new in 0.10.2: a JSON object, kept as DocumentMeta.appData (AppData)
|
|
718
|
+
dedupe?: boolean; // new in 0.10.2
|
|
654
719
|
};
|
|
655
720
|
```
|
|
656
721
|
|
|
@@ -669,6 +734,8 @@ The argument of [`files.ingest`](#filesingestinput).
|
|
|
669
734
|
| `ifExists` | `"fail" \| "replace"` | `"fail"` | What to do when a document of `id` is already there, as the store sees it for this scope. `"fail"`: an `IngestError` `"exists"` (status 409). `"replace"`: the document is deleted, then the new one is stored; only one of the same owner and scope. One of another owner or scope is `"exists"` too, even when its text is gone. A document that has expired is written over in both cases. The store is asked before the file is read and again just before the writes. While one ingest of this library stores `id`, another ingest of `id` is `"exists"`, whatever its `ifExists`. Replacing is not atomic for readers on other servers: for a moment the document is missing. New in 0.9.0. |
|
|
670
735
|
| `scope` | [`DocumentScope`](#documentscope) | none | Where the document belongs, such as `[userId, chatId]`. Every store call of the ingest carries it, and it is kept in `meta.scope`, a copy: only a caller of the same scope may use the document, segment by segment. Never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error` ([events](./events.md#documents-eventresults-and-eventresult)). Not valid: a `DocumentScopeError`. `null` counts as none. New in 0.9.0. |
|
|
671
736
|
| `original` | `{ ref: string }` | none | Where your application keeps the uploaded file: `ref`, 1 to 1,024 characters, which your [`OriginalsReader`](#originalsreader) understands, such as a path under the folder of `fileOriginals`. When `keepOriginals` lists the format, the store keeps no copy (`putOriginal` is not called), and the metadata records `original: { ref, bytes, sha256 }`; `originalKept` is true. Without `originals` in the library: a `TypeError`. A format `keepOriginals` does not list records nothing. The ref is never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error` ([events](./events.md#documents-eventresults-and-eventresult)). The library never writes, moves or deletes that file: `delete` and `sweep` leave it. [Storage](../guides/storage.md#keeping-the-uploaded-files). New in 0.9.0. |
|
|
737
|
+
| `appData` | `object` | none | Your application's own data about the document, kept as `DocumentMeta.appData` ([`AppData`](#documentmeta), JSON values): a JSON object (an interface type of yours fits), at most `MAX_APP_DATA_BYTES` (16,384) bytes as JSON in UTF-8, such as the ID of its row in your database or a label. It is copied through JSON, so what JSON leaves out (a function, `undefined`) is left out. Not an object (an array, a string), or something JSON cannot write (a `BigInt`, a loop): a `TypeError`; larger: a `RangeError`. `null` counts as none. Never sent to the model, nor in a summary; an event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error`. Change it later with [`files.update`](#filesupdateid-changes-access). New in 0.10.2. |
|
|
738
|
+
| `dedupe` | `boolean` | `false` | When the store already has a document of the same owner and scope whose file has the same SHA-256, and its text is still there, `ingest` gives back that document instead of storing another (H6): its ID, name and `appData` stay its own, and its expiry is counted again from now when the store has `patchMeta`; a document the store then says is gone (deleted meanwhile) is passed over. Its `createdAt` is before the call: an application that deletes what an ingest made when a later step fails must not delete this one. The file is read once to hash it, not extracted, and `ingest.finish` tells the document found. Never across owners or scopes. It reads the store's [`list`](#documentstore): a store without it is a `TypeError`; with `id` too, a `TypeError` (an application's ID names its own document). The document found is never removed for this ingest, even when its caller leaves or a listener throws. New in 0.10.2. |
|
|
672
739
|
|
|
673
740
|
Guide: [web app](../guides/web-app.md).
|
|
674
741
|
|
|
@@ -701,7 +768,9 @@ export const meta = await files.ingest({ name: "report.pdf", source: { path: "/s
|
|
|
701
768
|
(`ingestTimeoutMs`) begins at its turn, but this look, and the reads for its format (below), are
|
|
702
769
|
not waited for past it either (2 minutes when it is 0): a volume that does not answer fails the
|
|
703
770
|
ingest with an error of code `"ETIMEDOUT"` and `syscall` `"lstat"` or `"read"`, which names no
|
|
704
|
-
path. A caller that aborts `signal` meanwhile gets its own reason at once.
|
|
771
|
+
path. A caller that aborts `signal` meanwhile gets its own reason at once. Since 0.10.2 such a
|
|
772
|
+
look, and the read of the file when `ingestTimeoutMs` is a time limit, counts toward
|
|
773
|
+
`stats().stuckStoreCalls` past that time, until it ends, as a store call does.
|
|
705
774
|
- **Its format**: from its name and type, as for bytes. When they say nothing (no extension,
|
|
706
775
|
`application/octet-stream`), from its first KB, and for a ZIP from its first 64 KB and its last
|
|
707
776
|
MB, read for that alone: a DOCX without its extension is still a DOCX.
|
|
@@ -716,7 +785,8 @@ export const meta = await files.ingest({ name: "report.pdf", source: { path: "/s
|
|
|
716
785
|
- **An extractor that reads paths** (`Extractor.readsPath`, as those of
|
|
717
786
|
[`createIsolatedExtractors`](./node.md#createisolatedextractorsoptions) do) reads the file itself,
|
|
718
787
|
and the server reads none of it. When the store keeps a copy, the server reads it all the same,
|
|
719
|
-
and the extractor gets the bytes.
|
|
788
|
+
and the extractor gets the bytes. With `dedupe` (0.10.2), the server reads it once more to hash
|
|
789
|
+
it before the extractor runs, a slice at a time, keeping none of it.
|
|
720
790
|
- **The library never writes, moves or deletes the file.** Remove it yourself when you no longer
|
|
721
791
|
need it, or keep it and give `original: { ref }` so that its pages can be shown without a copy in
|
|
722
792
|
the store.
|
|
@@ -1090,6 +1160,12 @@ declare const DEFAULT_INGEST_TIMEOUT_MS = 120000; // 2 minutes
|
|
|
1090
1160
|
|
|
1091
1161
|
The default of `LargeFilesOptions.ingestTimeoutMs`. New in 0.6.0.
|
|
1092
1162
|
|
|
1163
|
+
### `MAX_APP_DATA_BYTES`
|
|
1164
|
+
|
|
1165
|
+
`const MAX_APP_DATA_BYTES = 16384`
|
|
1166
|
+
|
|
1167
|
+
New in 0.10.2. The most bytes [`DocumentMeta.appData`](#documentmeta) may take, as JSON in UTF-8.
|
|
1168
|
+
|
|
1093
1169
|
### `NEVER_EXPIRES`
|
|
1094
1170
|
|
|
1095
1171
|
```ts
|
|
@@ -1231,7 +1307,11 @@ interface DocumentStore {
|
|
|
1231
1307
|
readTextRange?(id: string, start: number, end: number, context?: DocumentContext): Promise<Uint8Array | undefined>;
|
|
1232
1308
|
putIndex?(id: string, index: Uint8Array, context?: DocumentContext): Promise<void>;
|
|
1233
1309
|
getIndex?(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
|
|
1310
|
+
list?(context?: DocumentContext): Promise<DocumentMeta[]>; // new in 0.10.2
|
|
1311
|
+
patchMeta?(id: string, patch: MetaPatch, context?: DocumentContext): Promise<DocumentMeta | undefined>; // new in 0.10.2
|
|
1234
1312
|
}
|
|
1313
|
+
|
|
1314
|
+
type MetaPatch = { createdAt: string; owner?: string; scope?: DocumentScope; expiresAt?: string; appData?: AppData | null }; // new in 0.10.2
|
|
1235
1315
|
```
|
|
1236
1316
|
|
|
1237
1317
|
Where the extracted text lives, with its metadata, and optionally the uploaded file and a line
|
|
@@ -1257,6 +1337,8 @@ A store that wraps another one, or a subclass that overrides a method, passes th
|
|
|
1257
1337
|
| `readTextRange(id, start, end)` | no | Bytes `start` (inclusive) to `end` (exclusive) of the text exactly as given to `put`, as UTF-8: the line index is built from those bytes. Return fewer bytes at the end of the text, and `undefined` when the document is gone. Called only after `getMeta` found the document. Without it, every document is loaded whole. |
|
|
1258
1338
|
| `putIndex(id, index)` | no | Keep the line index of a document (a few bytes a line). Called at ingest before `put`, and when a document ingested without an index is first read by range (an error then is ignored). Without it, the index is built from the text each time a large document is opened. |
|
|
1259
1339
|
| `getIndex(id)` | no | The index kept by `putIndex`, or `undefined`. A damaged one is noticed and built again. An error is taken as no index. |
|
|
1340
|
+
| `list()` | no | The metadata of the documents of `context.scope` (of no scope when it has none), in any order; it may leave out the expired ones or give them (the library leaves them out); a store that keeps no scopes apart may give every document, and the library keeps to the caller's. Called by [`files.list`](#fileslistaccess) and by `ingest({ dedupe: true })`. Without it, both are a `TypeError`. A store of many documents should answer from an index (a query on the scope), not by reading each one. New in 0.10.2. |
|
|
1341
|
+
| `patchMeta(id, patch)` | no | Change the fields of `patch` in the metadata of the document `id` whose `createdAt`, owner and scope are `patch.createdAt`, `patch.owner` and `patch.scope` (absent or null is none; scopes compared segment by segment), and nothing else: `expiresAt` becomes the later of the stored one and `patch.expiresAt`; `appData` is replaced, or removed when `null`; fields left out are not touched. Return the metadata as it is after the change, or `undefined`, writing nothing, when no such document is there: unknown, deleted, expired, or another one stored under the ID since (another `createdAt`, owner or scope). Apply the fields to what is stored when you write, not to a copy read before, so that a `touch` and an `update` at once both stay: a database does it in one conditional update. Called by [`files.touch`](#filestouchid-access), [`files.update`](#filesupdateid-changes-access) and `ingest({ dedupe: true })`. Without it, `touch` and `update` are a `TypeError`. New in 0.10.2. |
|
|
1260
1342
|
|
|
1261
1343
|
Errors:
|
|
1262
1344
|
|
|
@@ -1354,9 +1436,16 @@ declare class MemoryDocumentStore implements DocumentStore {
|
|
|
1354
1436
|
sweep(now?: Date, context?: DocumentContext): Promise<number>;
|
|
1355
1437
|
putOriginal(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void>;
|
|
1356
1438
|
getOriginal(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
|
|
1439
|
+
list(context?: DocumentContext): Promise<DocumentMeta[]>; // new in 0.10.2
|
|
1440
|
+
patchMeta(id: string, patch: MetaPatch, context?: DocumentContext): Promise<DocumentMeta | undefined>; // new in 0.10.2
|
|
1357
1441
|
}
|
|
1358
1442
|
```
|
|
1359
1443
|
|
|
1444
|
+
Since 0.10.2, a subclass that has its own `put`, `get`, `getMeta` or `delete` (a key prefix,
|
|
1445
|
+
encryption) and no `list` or `patchMeta` of its own is used as if it had neither: the built-in
|
|
1446
|
+
ones would go past its own. Give it its own to use `files.list`, `files.touch`, `files.update` and
|
|
1447
|
+
`dedupe`. The same holds for `FileDocumentStore`.
|
|
1448
|
+
|
|
1360
1449
|
Keeps documents, and kept originals, in the memory of the process: for tests, scripts and
|
|
1361
1450
|
one-process demos. They are lost on restart and not shared between processes. It has no
|
|
1362
1451
|
`readTextRange`, so every document is loaded whole, whatever `wholeDocumentBytes` says. `get` and
|
|
@@ -1394,6 +1483,8 @@ declare class FileDocumentStore implements DocumentStore {
|
|
|
1394
1483
|
readTextRange(id: string, start: number, end: number, context?: DocumentContext): Promise<Uint8Array | undefined>;
|
|
1395
1484
|
putIndex(id: string, index: Uint8Array, context?: DocumentContext): Promise<void>;
|
|
1396
1485
|
getIndex(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
|
|
1486
|
+
list(context?: DocumentContext): Promise<DocumentMeta[]>; // new in 0.10.2
|
|
1487
|
+
patchMeta(id: string, patch: MetaPatch, context?: DocumentContext): Promise<DocumentMeta | undefined>; // new in 0.10.2
|
|
1397
1488
|
}
|
|
1398
1489
|
```
|
|
1399
1490
|
|
|
@@ -1453,7 +1544,10 @@ documents of each scope are in a folder of their own:
|
|
|
1453
1544
|
removed itself, as `delete` does: of two sweeps at once, on one server or two, each document is
|
|
1454
1545
|
counted once (since 0.9.0; on Windows too since 0.10.0). It also
|
|
1455
1546
|
removes files that belong to no document, and temporary files, once they are older than
|
|
1456
|
-
`orphanAgeMs` (these are not counted).
|
|
1547
|
+
`orphanAgeMs` (these are not counted). Since 0.10.2 it also removes, and counts, a document whose
|
|
1548
|
+
metadata is there and whose text is gone, once the metadata is older than `orphanAgeMs` (only a
|
|
1549
|
+
file of the store's own: in a folder the application shares, one of a name the library makes).
|
|
1550
|
+
Where files
|
|
1457
1551
|
of your own may sit beside the documents (`directory` without `scopes`, or `scopes.folder` `""`),
|
|
1458
1552
|
a file of no document is removed only when its name is an ID the library makes, or a temporary
|
|
1459
1553
|
file: `notes.txt` may be yours, not the text of a document `notes`. A document whose metadata
|
|
@@ -2062,7 +2156,7 @@ browser instead.
|
|
|
2062
2156
|
| `metaVersion` | `number \| undefined` | The version of this shape: [`DOCUMENT_META_VERSION`](#document_meta_version) (1) on documents ingested by 0.9.0 and later, absent on older ones. A higher one is refused. Never sent to the model. New in 0.9.0. |
|
|
2063
2157
|
| `owner` | `string \| undefined` | The owner given at ingest. Absent when none was given. |
|
|
2064
2158
|
| `scope` | `string[] \| undefined` | The scope given at ingest (`IngestInput.scope`), as a copy. Absent when none was given. Only a caller of the same scope may use the document. Never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error` ([events](./events.md#documents-eventresults-and-eventresult)). New in 0.9.0. |
|
|
2065
|
-
| `sha256` | `string \| undefined` | The SHA-256 of the uploaded file, as 64 lowercase hex digits. Always set by 0.9.0 and later, for bytes and for a path; absent on older documents. A kept copy in the store is checked against it when it is read back.
|
|
2159
|
+
| `sha256` | `string \| undefined` | The SHA-256 of the uploaded file, as 64 lowercase hex digits. Always set by 0.9.0 and later, for bytes and for a path; absent on older documents. A kept copy in the store is checked against it when it is read back. Since 0.10.2, `ingest({ dedupe: true })` gives back the document of the same owner and scope with the same SHA-256 instead of storing another ([`IngestInput`](#ingestinput)). Never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error` ([events](./events.md#documents-eventresults-and-eventresult)). New in 0.9.0. |
|
|
2066
2160
|
| `original` | `{ ref, bytes, sha256 } \| undefined` | Where your application keeps the uploaded file (`IngestInput.original.ref`), with its size and SHA-256 at ingest, which each read is checked against. Set when the file is kept by its ref; absent for a copy in the store. The ref is never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error` ([events](./events.md#documents-eventresults-and-eventresult)). New in 0.9.0. |
|
|
2067
2161
|
| `name` | `string` | The cleaned file name (see [`IngestInput`](#ingestinput)). |
|
|
2068
2162
|
| `mimeType` | `string` | The MIME type given, cleaned since 0.9.0 to a lowercased type/subtype without parameters (see [`IngestInput`](#ingestinput)), or `"application/octet-stream"`. |
|
|
@@ -2084,7 +2178,8 @@ browser instead.
|
|
|
2084
2178
|
| `garbledPages` | `number[]` or `undefined` | The pages of a PDF whose text looks garbled: of at least 40 characters, fewer than 3 in 10 letters or digits, or more than max(6, 3%) replacement characters (a font without a Unicode map). Up to 200. The card says not to rely on them. New in 0.8.1. |
|
|
2085
2179
|
| `scripts` | `{ script, percent }[]` or `undefined` | The scripts of the text by their share of its letters, from its first 2 MB, those of 5% or more: "Latin", "Hebrew", "Arabic", "Cyrillic", "Greek", "CJK", "Devanagari", "Thai". Absent for a text in Latin letters alone, one with fewer than 200 letters, and documents from before 0.8.1. The card says "Written in: Hebrew 81%, Latin 19%. Search in the language of the text." New in 0.8.1. |
|
|
2086
2180
|
| `createdAt` | `string` | When it was ingested, as an ISO 8601 date. |
|
|
2087
|
-
| `expiresAt` | `string` | When it expires, as an ISO 8601 date: `createdAt` plus `ttlMs`, or [`NEVER_EXPIRES`](#never_expires). |
|
|
2181
|
+
| `expiresAt` | `string` | When it expires, as an ISO 8601 date: `createdAt` plus `ttlMs`, or [`NEVER_EXPIRES`](#never_expires). Since 0.10.2, [`files.touch`](#filestouchid-access) counts it again from the time of the call. |
|
|
2182
|
+
| `appData` | `AppData \| undefined` | Your application's own data about the document: a JSON object (`{ [key: string]: JsonValue }`) of at most `MAX_APP_DATA_BYTES` (16 KB) as JSON, set at ingest ([`IngestInput.appData`](#ingestinput)) or by [`files.update`](#filesupdateid-changes-access). The library keeps it with the metadata and does nothing else with it: never sent to the model, nor in a summary. An event holds it only with `eventResults: true`, in the full plan of `run.finish` and `run.error`. Absent when none was given. New in 0.10.2. |
|
|
2088
2183
|
|
|
2089
2184
|
### `DocumentSummary`
|
|
2090
2185
|
|
|
@@ -228,6 +228,10 @@ What the checks cover:
|
|
|
228
228
|
left shows when a document is put again under the ID. With `isolatesScopes`, a sweep with a scope
|
|
229
229
|
removes only that scope's.
|
|
230
230
|
- The IDs an application may choose ([`APP_DOCUMENT_ID_PATTERN`](./library.md#app_document_id_pattern)).
|
|
231
|
+
- Since 0.10.2, when the store has them: `list` gives the documents of a scope, not the deleted
|
|
232
|
+
ones, as copies ("list"); `patchMeta` changes its fields alone, only for the document of that
|
|
233
|
+
`createdAt`, owner and scope, keeps the later expiry, and keeps both of two changes made at once
|
|
234
|
+
("meta").
|
|
231
235
|
- Every method takes a context. Without `requiresScope`, also no context, `{}`, and an owner alone.
|
|
232
236
|
- With `requiresScope`: a call without a scope throws a
|
|
233
237
|
[`DocumentScopeError`](./library.md#documentscopeerror) of code `"scope_required"`, and `sweep`
|
|
@@ -245,13 +249,15 @@ What the checks cover:
|
|
|
245
249
|
|
|
246
250
|
Each check makes its own store with `create`, over storage of its own (`environment.storage`), and
|
|
247
251
|
gives every store it made to `dispose` at the end. The checks pass a scope (and an owner) on most
|
|
248
|
-
calls.
|
|
249
|
-
|
|
252
|
+
calls. A check a patch release adds runs only for a method the store did not have before (0.10.2:
|
|
253
|
+
`list` and `patchMeta`, checked only when the store has them, and for a subclass of a built-in store
|
|
254
|
+
with its own `put`, `get`, `getMeta` or `delete` only when it has its own), so a patch release never
|
|
255
|
+
fails a store that passed.
|
|
250
256
|
|
|
251
257
|
### `DocumentStoreChecksOptions`
|
|
252
258
|
|
|
253
259
|
```ts
|
|
254
|
-
type StoreCheckPart = "originals" | "ranges" | "index" | "sweep" | "shared";
|
|
260
|
+
type StoreCheckPart = "originals" | "ranges" | "index" | "sweep" | "shared" | "list" | "meta"; // "list", "meta": new in 0.10.2
|
|
255
261
|
|
|
256
262
|
type DocumentStoreChecksOptions = {
|
|
257
263
|
create(environment: StoreCheckEnvironment): DocumentStore | Promise<DocumentStore>;
|
|
@@ -270,7 +276,7 @@ type DocumentStoreChecksOptions = {
|
|
|
270
276
|
| `isolatesScopes` | `false` | The store keeps the documents of each scope apart, as `MemoryDocumentStore` and a scoped `FileDocumentStore` do. Adds the checks of scopes. Leave it false for a store that ignores the context: the library then keeps scopes apart by `meta.scope`. |
|
|
271
277
|
| `requiresScope` | `false` | The store refuses a call without a scope, as a `FileDocumentStore` with `scopes` does. The checks then always pass one, and one more checks the refusal. |
|
|
272
278
|
| `scopeDepth` | `2` | How many segments the scopes of the checks have, from 1 to 8: `["user-1", "chat-a"]` with 2. |
|
|
273
|
-
| `skip` | `[]` | The parts the store does not have: `"originals"` (`putOriginal` and `getOriginal`), `"ranges"` (`readTextRange`), `"index"` (`putIndex` and `getIndex`), `"sweep"`, and `"shared"` for storage two stores cannot share (`MemoryDocumentStore`). A check of a part the store lacks, not skipped, fails and says to skip it. |
|
|
279
|
+
| `skip` | `[]` | The parts the store does not have: `"originals"` (`putOriginal` and `getOriginal`), `"ranges"` (`readTextRange`), `"index"` (`putIndex` and `getIndex`), `"sweep"`, and `"shared"` for storage two stores cannot share (`MemoryDocumentStore`). A check of a part the store lacks, not skipped, fails and says to skip it. Since 0.10.2, `"list"` (`list`) and `"meta"` (`patchMeta`): those are checked only when the store has them, so a store written for 0.10.1 passes as before; `skip` leaves them out for a store that has them. |
|
|
274
280
|
|
|
275
281
|
`documentStoreChecks` throws a `TypeError` without `create`, or for a `scopeDepth` outside 1 to 8.
|
|
276
282
|
|
package/docs/security.md
CHANGED
|
@@ -1131,7 +1131,8 @@ What does hold per library (per `createLargeFiles` call, so per process when you
|
|
|
1131
1131
|
per process, as [Deployment](./guides/deployment.md#what-lives-where) advises): scans of documents
|
|
1132
1132
|
read by range (searches, counting the parts of a file) run at most `maxConcurrentScans` (4) at a
|
|
1133
1133
|
time, and the others wait their turn; the documents kept ready in memory between tool calls take at
|
|
1134
|
-
most `cacheBytes` (256 MB).
|
|
1134
|
+
most `cacheBytes` (256 MB), and since 0.10.2 one more, the last larger than that, for a minute after
|
|
1135
|
+
its last use.
|
|
1135
1136
|
|
|
1136
1137
|
## What a question can cost
|
|
1137
1138
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "llm-large-files",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.2",
|
|
4
4
|
"description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, a look at the pages of a PDF, and one tool loop for any model. Adapters for Gemini and Vertex AI, OpenAI-compatible endpoints, and Claude.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"llm",
|
package/src/ask.ts
CHANGED
|
@@ -257,6 +257,14 @@ export type AskOptions = {
|
|
|
257
257
|
* documents, and events are often sent on to a browser.
|
|
258
258
|
*/
|
|
259
259
|
eventResults?: boolean;
|
|
260
|
+
/**
|
|
261
|
+
* How `AskResult.toolTurns` holds the results of the question's tool calls. "full" (the default):
|
|
262
|
+
* as the model had them. "compact": each large result replaced by the stand-in the loop sends
|
|
263
|
+
* when it drops a result to make room (`compactToolTurns`), so that a stored question takes a few
|
|
264
|
+
* hundred bytes a call. A later question then sends those stand-ins: the model reads again what it
|
|
265
|
+
* needs, at the price of a tool call. New in 0.10.2.
|
|
266
|
+
*/
|
|
267
|
+
storeRounds?: "full" | "compact";
|
|
260
268
|
signal?: AbortSignal;
|
|
261
269
|
};
|
|
262
270
|
|
|
@@ -369,6 +377,29 @@ function checkFilteredAnswer(given: unknown): void {
|
|
|
369
377
|
throw new TypeError(`filteredAnswer must be "keep" or "drop", and is ${shownValue(given)}.`);
|
|
370
378
|
}
|
|
371
379
|
|
|
380
|
+
/** `storeRounds` checked: "full", "compact" or nothing (0.10.2). */
|
|
381
|
+
function checkStoreRounds(given: unknown): void {
|
|
382
|
+
if (given === undefined || given === "full" || given === "compact") return;
|
|
383
|
+
throw new TypeError(`storeRounds must be "full" or "compact", and is ${shownValue(given)}.`);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Stored tool rounds (`AskResult.toolTurns`) made small: each result that is large is replaced by
|
|
388
|
+
* the stand-in the loop sends when it drops a result to make room (`stubResult`): the document, the
|
|
389
|
+
* lines or pages it showed, a search's query and total, the largest groups of a count, and a note
|
|
390
|
+
* that it was dropped. Errors and small results stay as they are. Copies: the turns given are not
|
|
391
|
+
* changed. For rounds stored by `storeRounds: "full"`, or by an earlier version. New in 0.10.2.
|
|
392
|
+
*/
|
|
393
|
+
export function compactToolTurns(turns: readonly ToolTurn[]): ToolTurn[] {
|
|
394
|
+
return turns.map((turn) => ({
|
|
395
|
+
...turn,
|
|
396
|
+
calls: turn.calls.map((call) => {
|
|
397
|
+
const { result, ...rest } = call;
|
|
398
|
+
return { ...rest, result: stubResult(rest, result) ?? result };
|
|
399
|
+
}),
|
|
400
|
+
}));
|
|
401
|
+
}
|
|
402
|
+
|
|
372
403
|
/**
|
|
373
404
|
* `inlineTables` and `numberInline` checked: a value they cannot be ("Text", "false") is an error
|
|
374
405
|
* before anything is planned, as `prepare` would throw it, but in the words of the question.
|
|
@@ -977,6 +1008,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
977
1008
|
const limits = checkedLimits(options.limits);
|
|
978
1009
|
checkMissingPolicy(options.onMissingDocuments);
|
|
979
1010
|
checkFilteredAnswer(options.filteredAnswer);
|
|
1011
|
+
checkStoreRounds(options.storeRounds);
|
|
980
1012
|
checkInlineOptions(options.inlineTables, options.numberInline);
|
|
981
1013
|
// Since 0.10.0 by default: the tables sent whole get the tools, and the files sent whole have
|
|
982
1014
|
// numbered lines. "text" and false send them as 0.9 did.
|
|
@@ -1277,13 +1309,14 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1277
1309
|
...(blockReason ? { blockReason } : {}),
|
|
1278
1310
|
steps,
|
|
1279
1311
|
evidence,
|
|
1280
|
-
// The rounds as the model last had them
|
|
1312
|
+
// The rounds as the model last had them, or their stand-ins (`storeRounds: "compact"`). A
|
|
1313
|
+
// file cannot be kept as JSON: what is kept says that it was shown.
|
|
1281
1314
|
toolTurns: messages.slice(asked).filter(isRound).map((round) => ({
|
|
1282
1315
|
role: "tools" as const,
|
|
1283
1316
|
version: TOOL_TURN_VERSION,
|
|
1284
1317
|
calls: round.answers.map(({ call: { problem: _problem, ...call }, result: returned, files: shownFiles }) => ({
|
|
1285
1318
|
...call,
|
|
1286
|
-
result: shownFiles?.length ? stubResult(call, returned, true) ?? returned : returned,
|
|
1319
|
+
result: shownFiles?.length ? stubResult(call, returned, true) ?? returned : options.storeRounds === "compact" ? stubResult(call, returned) ?? returned : returned,
|
|
1287
1320
|
})),
|
|
1288
1321
|
})),
|
|
1289
1322
|
plan: prepared.plan,
|
package/src/cache.ts
CHANGED
|
@@ -36,10 +36,18 @@ export function documentVersion(meta: DocumentMeta): string {
|
|
|
36
36
|
* not served from here.
|
|
37
37
|
*/
|
|
38
38
|
export class DocumentCache<T extends Sized> {
|
|
39
|
-
private readonly entries = new Map<string, { version: string; value: T; bytes: number; owner?: string }>();
|
|
39
|
+
private readonly entries = new Map<string, { version: string; value: T; bytes: number; owner?: string; used: number }>();
|
|
40
|
+
/** A count of uses, to tell which of the documents and the one kept apart was used longest ago. */
|
|
41
|
+
private uses = 0;
|
|
40
42
|
/** Entries that belong to no other: the documents. */
|
|
41
43
|
private documents = 0;
|
|
42
44
|
private total = 0;
|
|
45
|
+
/**
|
|
46
|
+
* The last document larger than the whole cache, kept apart for `OVERSIZE_KEEP_MS` after its
|
|
47
|
+
* last use (P4, 0.10.2): the tool calls of one question that read it again do not each load and
|
|
48
|
+
* index it again, as they did over a store without `readTextRange`. One at most.
|
|
49
|
+
*/
|
|
50
|
+
private oversize: { id: string; version: string; value: T; bytes: number; timer: ReturnType<typeof setTimeout>; used: number } | undefined;
|
|
43
51
|
|
|
44
52
|
constructor(
|
|
45
53
|
private readonly maxBytes: number,
|
|
@@ -47,9 +55,9 @@ export class DocumentCache<T extends Sized> {
|
|
|
47
55
|
private readonly maxEntries = Number.POSITIVE_INFINITY,
|
|
48
56
|
) {}
|
|
49
57
|
|
|
50
|
-
/** Memory taken by the cached documents, by their own estimate. */
|
|
58
|
+
/** Memory taken by the cached documents, by their own estimate: the last oversize document too. */
|
|
51
59
|
get bytes(): number {
|
|
52
|
-
return this.total;
|
|
60
|
+
return this.total + (this.oversize?.bytes ?? 0);
|
|
53
61
|
}
|
|
54
62
|
|
|
55
63
|
get size(): number {
|
|
@@ -58,13 +66,14 @@ export class DocumentCache<T extends Sized> {
|
|
|
58
66
|
|
|
59
67
|
get(id: string, version: string): T | undefined {
|
|
60
68
|
const entry = this.entries.get(id);
|
|
61
|
-
if (!entry) return
|
|
69
|
+
if (!entry) return this.lastOversize(id, version);
|
|
62
70
|
if (entry.version !== version) {
|
|
63
71
|
this.delete(id);
|
|
64
72
|
return undefined;
|
|
65
73
|
}
|
|
66
74
|
// Most recently used last.
|
|
67
75
|
this.entries.delete(id);
|
|
76
|
+
entry.used = ++this.uses;
|
|
68
77
|
this.entries.set(id, entry);
|
|
69
78
|
return entry.value;
|
|
70
79
|
}
|
|
@@ -78,23 +87,19 @@ export class DocumentCache<T extends Sized> {
|
|
|
78
87
|
if (existing?.value === value && existing.version === version) return;
|
|
79
88
|
this.delete(id);
|
|
80
89
|
const bytes = Math.max(0, value.memoryBytes);
|
|
81
|
-
if (
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
let oldest: string | undefined;
|
|
88
|
-
for (const [key, entry] of this.entries) {
|
|
89
|
-
if (entry.owner === undefined) {
|
|
90
|
-
oldest = key;
|
|
91
|
-
break;
|
|
92
|
-
}
|
|
90
|
+
if (this.maxEntries < 1) return;
|
|
91
|
+
if (bytes > this.maxBytes) {
|
|
92
|
+
// A document (not a piece), with a cache that keeps any: the last one is kept apart.
|
|
93
|
+
if (owner === undefined && this.maxBytes > 0) {
|
|
94
|
+
this.keepOversize(id, version, value, bytes);
|
|
95
|
+
this.withinEntries();
|
|
93
96
|
}
|
|
94
|
-
|
|
95
|
-
this.delete(oldest);
|
|
96
|
-
for (const [key, entry] of [...this.entries]) if (entry.owner === oldest) this.delete(key);
|
|
97
|
+
return;
|
|
97
98
|
}
|
|
99
|
+
this.entries.set(id, { version, value, bytes, ...(owner !== undefined ? { owner } : {}), used: ++this.uses });
|
|
100
|
+
this.total += bytes;
|
|
101
|
+
if (owner === undefined) this.documents++;
|
|
102
|
+
this.withinEntries();
|
|
98
103
|
// Too much memory: the entries used longest ago go, whatever they are.
|
|
99
104
|
for (const [oldest] of this.entries) {
|
|
100
105
|
if (this.total <= this.maxBytes) break;
|
|
@@ -103,6 +108,7 @@ export class DocumentCache<T extends Sized> {
|
|
|
103
108
|
}
|
|
104
109
|
|
|
105
110
|
delete(id: string): void {
|
|
111
|
+
if (this.oversize?.id === id) this.dropOversize();
|
|
106
112
|
const entry = this.entries.get(id);
|
|
107
113
|
if (!entry) return;
|
|
108
114
|
this.entries.delete(id);
|
|
@@ -117,6 +123,76 @@ export class DocumentCache<T extends Sized> {
|
|
|
117
123
|
|
|
118
124
|
/** Drops every entry whose key passes `test`: one document in every scope, with its pieces. */
|
|
119
125
|
deleteWhere(test: (key: string) => boolean): void {
|
|
126
|
+
if (this.oversize && test(this.oversize.id)) this.dropOversize();
|
|
120
127
|
for (const key of [...this.entries.keys()]) if (test(key)) this.delete(key);
|
|
121
128
|
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Within `maxEntries` documents, the one kept apart counted (`cacheSize`): one too many, the
|
|
132
|
+
* document used longest ago goes, with what belongs to it, whether it is one of the others or the
|
|
133
|
+
* one kept apart.
|
|
134
|
+
*/
|
|
135
|
+
private withinEntries(): void {
|
|
136
|
+
while (this.documents + (this.oversize ? 1 : 0) > this.maxEntries) {
|
|
137
|
+
let oldest: string | undefined;
|
|
138
|
+
for (const [key, entry] of this.entries) {
|
|
139
|
+
if (entry.owner === undefined) {
|
|
140
|
+
oldest = key;
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const apart = this.oversize;
|
|
145
|
+
if (oldest === undefined || (apart && apart.used < this.entries.get(oldest)!.used)) {
|
|
146
|
+
this.dropOversize();
|
|
147
|
+
if (oldest === undefined) break;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
this.delete(oldest);
|
|
151
|
+
for (const [key, entry] of [...this.entries]) if (entry.owner === oldest) this.delete(key);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The last oversize document, when it is this one: its time is counted again from now. */
|
|
156
|
+
private lastOversize(id: string, version: string): T | undefined {
|
|
157
|
+
const kept = this.oversize;
|
|
158
|
+
if (kept?.id !== id) return undefined;
|
|
159
|
+
if (kept.version !== version) {
|
|
160
|
+
this.dropOversize();
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
kept.timer = this.oversizeTimer(kept.timer);
|
|
164
|
+
kept.used = ++this.uses;
|
|
165
|
+
return kept.value;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private keepOversize(id: string, version: string, value: T, bytes: number): void {
|
|
169
|
+
this.dropOversize();
|
|
170
|
+
this.oversize = { id, version, value, bytes, timer: this.oversizeTimer(), used: ++this.uses };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The timer that lets the document kept apart go: `timer` counted again from now, or a new one.
|
|
175
|
+
* It does not keep the process alive, and it holds the cache weakly: a library let go of with a
|
|
176
|
+
* document kept apart is collected at once, not a minute later with everything it kept.
|
|
177
|
+
*/
|
|
178
|
+
private oversizeTimer(timer?: ReturnType<typeof setTimeout>): ReturnType<typeof setTimeout> {
|
|
179
|
+
if (timer && typeof timer.refresh === "function") {
|
|
180
|
+
timer.refresh();
|
|
181
|
+
return timer;
|
|
182
|
+
}
|
|
183
|
+
if (timer) clearTimeout(timer);
|
|
184
|
+
const cache = new WeakRef(this);
|
|
185
|
+
const next = setTimeout(() => cache.deref()?.dropOversize(), OVERSIZE_KEEP_MS);
|
|
186
|
+
next.unref?.();
|
|
187
|
+
return next;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private dropOversize(): void {
|
|
191
|
+
if (!this.oversize) return;
|
|
192
|
+
clearTimeout(this.oversize.timer);
|
|
193
|
+
this.oversize = undefined;
|
|
194
|
+
}
|
|
122
195
|
}
|
|
196
|
+
|
|
197
|
+
/** How long the last document larger than the whole cache is kept after its last use (P4). New in 0.10.2. */
|
|
198
|
+
export const OVERSIZE_KEEP_MS = 60_000;
|
package/src/index.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
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_INGEST_TIMEOUT_MS, DEFAULT_MAX_PDF_PAGES, DEFAULT_MAX_TEXT_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, MAX_APP_DATA_BYTES, NEVER_EXPIRES, toDocumentSummary } from "./library.js";
|
|
5
5
|
export type { AccessOptions, CreatedLargeFiles, IngestFromSource, IngestInput, IngestSource, LargeFiles, LargeFilesOptions, LargeFilesStats, OriginalReadContext, OriginalsReader, PrepareOptions, ToolOptions } from "./library.js";
|
|
6
6
|
export { DEFAULT_BUDGET, resolveBudget } from "./budget.js";
|
|
7
7
|
export type { ModelLimits } from "./budget.js";
|
|
8
|
-
export { askStream, askWithFiles, DEFAULT_INPUT_TOKENS, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "./ask.js";
|
|
8
|
+
export { askStream, askWithFiles, compactToolTurns, DEFAULT_INPUT_TOKENS, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "./ask.js";
|
|
9
9
|
export type { AskLimits, AskOptions, AskResult, MissingDocumentsAction, MissingDocumentsContext, ToolResultContext, ToolResultVerdict } from "./ask.js";
|
|
10
10
|
export * from "./answer-info.js";
|
|
11
11
|
export * from "./citations.js";
|